1

There are one file 'foo.txt' where 'koushik' is written. code:-

   var fs = require('fs');
   var rr = fs.createReadStream('foo.txt');
   rr.on('readable', function() {
     console.log('readable:', rr.read(1));
   });
   rr.on('end', function() {
     console.log('end');
   });

output:-

k
o
Alex Wayne
  • 178,991
  • 47
  • 309
  • 337
Koushik Mondal
  • 865
  • 7
  • 15

1 Answers1

0

The readable event is emitted when there is data available to be read from the stream.

The read(1) you have in that event handler will read one byte from the currently available data, each time the readable event fires.

It triggers twice because the file handling in node.js decides to fire it twice.

You may get the output you expect if you instead use no argument to read()

var fs = require('fs');
var rr = fs.createReadStream('foo.txt');
rr.on('readable', function() {
  console.log('readable:', rr.read()); // read all available data
});
rr.on('end', function() {
  console.log('end');
});
Alex Wayne
  • 178,991
  • 47
  • 309
  • 337