Why createReadStream instance of Buffer showing false?


#1

I was practicing stream. The code below works fine put put me in a tough situation to figure out 2 things:

  1. Why I am getting this output twice :

    typeof d :object
    false

  2. 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'))
})

#2

To quote the node.js documentation:
"The 'readable' event will also be emitted once the end of the stream data has been reached but before the 'end' event is emitted."


This is the part i'm not sure on. The second time through, d should be null...
what happens if you tell it to flat out console.log(d) ?


#3

console.log(d) : d -> null
I believe d is flushed. But that is understandable . Do you know any one who can answer my second question?


#4

What does it output the other time it runs (the one with what you expect to be a Buffer)?


#5

Actually the following is true even though d instanceof Buffer is false. May be somehow it becomes true when goes to the if else. It's an assumption

else if (typeof d == 'object' && d instanceof Buffer) {
            str = d.toString('utf8')

#6

first impulse: Theory: instanceof has a lower priority than &&.
Try else if ((typeof d == 'object') && (d instanceof Buffer)) {


#7

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.