0

I am learning node js and I am at the sterams module.

I have below query - What is the difference between these two statements.

const {Readable} = require("stream") 
and 
const  Readable  = require("stream") 

Below Code Snippet works . Means data is emitted by Read Stream and end of stream is also raised.

But when const {Readable} is converted to const Readable , it stops working

Can anybody help why this behaviour ?

const {Readable} = require("stream"); // changing const Readable = require("stream") doesn't work 

const createReadStream = () => {

    const data = ["one","two","three"];

    return new Readable({

        read(){
            if (data.length === 0) {
                console.log('data ended');
                this.push(null);
            } else{
                console.log('reading data');
                this.push(data.shift());
            }
        }
    });

}
Atul
  • 1,560
  • 5
  • 30
  • 75

1 Answers1

1

These two:

const {Readable} = require("stream"); 

const  Readable  = require("stream"); 

Are not the same and the second will clearly not work. The second assigned the whole module handle to Readable whereas the first assigns the .Readable property in the module to your variable Readable. Perhaps what you meant to compare is these two:

const {Readable} = require("stream"); 

const Readable = require("stream").Readable; 

These two are pretty much equivalent. The const {Readable} syntax is called destructuring and is a shortcut for the syntax in the second line.


Note, the destructuring syntax really shows its advantages when you are fetching multiple properties at once:

const {Readable, Writable, Transform, pipeline} = require("stream");

As this declares and initializes multiple variables in one line of code.

jfriend00
  • 683,504
  • 96
  • 985
  • 979