Retsam
Retsam

Reputation: 33399

Node.js Readable file stream not getting data

I'm attempting to create a Readable file stream that I can read individual bytes from. I'm using the code below.

var rs = fs.createReadStream(file).on('open', function() {
    var buff = rs.read(8); //Read first 8 bytes
    console.log(buff);
});

Given that file is an existing file of at least 8 bytes, why am I getting 'null' as the output for this?

Upvotes: 5

Views: 6794

Answers (2)

user568109
user568109

Reputation: 48003

Event open means that stream has been initialized, it does not mean you can read from the stream. You would have to listen for either readable or data events.

var rs = fs.createReadStream(file);

rs.once('readable', function() {
    var buff = rs.read(8); //Read first 8 bytes only once
    console.log(buff.toString());
});

Upvotes: 5

Gates VP
Gates VP

Reputation: 45287

It looks like you're calling this rs.read() method. However, that method is only available in the Streams interface. In the Streams interface, you're looking for the 'data' event and not the 'open' event.

That stated, the docs actually recommend against doing this. Instead you should probably be handling chunks at a time if you want to stream them:

var rs = fs.createReadStream('test.txt');

rs.on('data', function(chunk) {
    console.log(chunk);
});

If you want to read just a specific portion of a file, you may want to look at fs.open() and fs.read() which are lower level.

Upvotes: 0

Related Questions