Javatpoint Logo
Javatpoint Logo

Node.js Streams

Streams are the objects that facilitate you to read data from a source and write data to a destination. There are four types of streams in Node.js:

  • Readable: This stream is used for read operations.
  • Writable: This stream is used for write operations.
  • Duplex: This stream can be used for both read and write operations.
  • Transform: It is type of duplex stream where the output is computed according to input.

Each type of stream is an Event emitter instance and throws several events at different times. Following are some commonly used events:

  • Data:This event is fired when there is data available to read.
  • End:This event is fired when there is no more data available to read.
  • Error: This event is fired when there is any error receiving or writing data.
  • Finish:This event is fired when all data has been flushed to underlying system.

Node.js Reading from stream

Create a text file named input.txt having the following content:

Create a JavaScript file named main.js having the following code:

File: main.js

Now, open the Node.js command prompt and run the main.js

Output:

Node.js streams 1

Node.js Writing to stream

Create a JavaScript file named main.js having the following code:

File: main.js

Now open the Node.js command prompt and run the main.js

You will see the following result:

Node.js streams 2

Now, you can see that a text file named "output.txt" is created where you had saved "input.txt" and "main.js" file. In my case, it is on desktop.

Open the "output.txt" and you will see the following content.

Node.js streams 3

Node.js Piping Streams

Piping is a mechanism where output of one stream is used as input to another stream. There is no limit on piping operation.

Let's take a piping example for reading from one file and writing it to another file.

File: main.js

Open the Node.js and run the mian.js

Node.js streams 4

Now, you can see that a text file named "output.txt" is created where you had saved ?main.js? file. In my case, it is on desktop.

Open the "output.txt" and you will see the following content.

Node.js streams 5

Node.js Chaining Streams

Chaining stream is a mechanism of creating a chain of multiple stream operations by connecting output of one stream to another stream. It is generally used with piping operation.

Let's take an example of piping and chaining to compress a file and then decompress the same file.

File: main.js

Open the Node.js command prompt and run main.js

You will get the following result:

Node.js streams 6

Now you will see that file "input.txt" is compressed and a new file is created named "input.txt.gz" in the current file.

To Decompress the same file: put the following code in the js file "main.js"

File: main.js

Open the Node.js command prompt and run main.js

Node.js streams 7



Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA