fs.read'ing a stream.fd

49 views
Skip to first unread message

Volkan Yazıcı

unread,
Nov 10, 2012, 3:00:40 PM11/10/12
to nod...@googlegroups.com
Hi! I am having trouble while fs.read'ing from fd of a stream. For instance, below script produces no outputs. What am I missing?

var fs = require("fs"),
    s = fs.createReadStream(__filename),
    l = 8192,
    b = new Buffer(l);

s.on("open", function() {
        fs.read(s.fd, b, 0, l, function (err, nbytes) {
                console.log(
                        "err: " + err + ", " +
                        "nbytes: " + nbytes + ", " +
                        "buf: " + b.toString(0, nbytes));
        });
});

Martin Cooper

unread,
Nov 10, 2012, 3:56:40 PM11/10/12
to nod...@googlegroups.com
You're mixing up two different approaches to reading the file.

When you use fs.createReadStream(), the file will be read automatically as a stream, and you'll start seeing 'data' events with chunks of data as they're read. With this model, you don't do the reading, the stream does it for you.

On the other hand, if you want to read the file manually, you'll need to open it using fs.open() first. Then you can use fs.read() calls to get the data.

I'd recommend the stream approach, unless there's some reason you can't do that.

--
Martin Cooper



--
Job Board: http://jobs.nodejs.org/
Posting guidelines: https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
You received this message because you are subscribed to the Google
Groups "nodejs" group.
To post to this group, send email to nod...@googlegroups.com
To unsubscribe from this group, send email to
nodejs+un...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/nodejs?hl=en?hl=en

Volkan Yazıcı

unread,
Nov 10, 2012, 4:07:46 PM11/10/12
to nod...@googlegroups.com
The problem is some libraries operate on fds to consume the input partially. (E.g., consider parsing the header of a binary file. Library first makes some read()'s, and by looking at the result of those read()'s, maybe some more read()'s too, etc.) OTOH, in my case, the input is piped through some other library which provides you a stream. And I need to pipe that stream to some other library that asks for a fd. Any recommendations?
Reply all
Reply to author
Forward
0 new messages