4

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?

Retsam
  • 30,909
  • 11
  • 68
  • 90

2 Answers2

5

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());
});
user568109
  • 47,225
  • 17
  • 99
  • 123
  • I cannot use your second method, `rs.read(8)` always returns null. I can only read if I wait for the event `readable`. – ffleandro Jan 05 '14 at 14:22
  • @ffleandro I have removed that part. I guess it doesn't work anymore. This first method is the correct way to read. – user568109 Jan 05 '14 at 17:05
0

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.

Gates VP
  • 44,957
  • 11
  • 105
  • 108
  • 1
    Won't attaching a data handler cause the stream to go into flowing mode? I probably should have specified that I wanted to use non-flowing mode in the question. – Retsam Aug 12 '13 at 20:37
  • Yeah, I had been working at the lower level, before attempting streams. I liked the certainty of `rs.read` always returning the right number of bytes (or null, if there aren't that many), rather than fs.read, which may return fewer bytes than requested. – Retsam Aug 12 '13 at 20:53