I was practicing stream. The code below works fine put put me in a tough situation to figure out 2 things:
-
Why I am getting this output twice :
typeof d :object
false -
why d instanceof Buffer is false. if False then how streaming is working in the else if condition?
var fs = require('fs');
var contents;
var rs = fs.createReadStream("simple_stream.js");
rs.on('readable', () => {
var str;
var d = rs.read();
console.log("typeof d :"+typeof d);
console.log("d instanceof Buffer: "+d instanceof Buffer)
if (d) {
if (typeof d == 'string') {
str = d;
} else if (typeof d == 'object' && d instanceof Buffer) {
str = d.toString('utf8')
}
if (str) {
if (!contents)
contents = d;
else contents += str;
}
}
});
rs.on('end', () => {
console.log("read in the file contents");
console.log(contents.toString('utf8'))
})