Loading, please wait...

Streams in Node.js

A stream is an abstract interface implemented by various objects in Node.js. Because of asynchronous and event-driven nature of Node.js, it is very good at handling I/O bound tasks and streams. These are actually Unix pipes.

Example: A request to an HTTP server is a stream. A request is a readable stream and response is a writable stream. Streams read data from a source and write data to the destination, it also mentions that streams are a collection of data just like arrays and strings.

Types of Streams:

  • Readable: Used for Read operation.
  • Writable: Used for Write operation.
  • Duplex: Used for both Read and write operation (for Example TCP socket)
  • Transform: It is a type of duplex stream where the output is computed according to input

Each type of stream is an Event emitter instance and it throws several events at various times.

Commonly used events are the following:

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

Reading From Stream:

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

In nodeProject.js

Execute the above program

Writing from a stream

Create a js file named nodeProject.js with the following Code.

Run the above code:

Open text.txt created in your current directory, it should contain the following-

Tutorials Link is E-learning portal

Piping the Streams

Piping is a technique where we provide the output of one stream as the input to another stream. It is normally used to get data from one stream and to pass the output of that stream to another stream.

Example of piping stream:

Run the above program

Open output.txt created in your current directory; it should contain the following:

Tutorials Link is learning content!!!!!

Chaining the stream

Chaining is a mechanism to connect the output of one stream to another stream and create a chain of multiple stream operations. It is generally used with piping operations.

Create a js file named node.js with the following code –

When you will run the above code, it will generate ‘input . txt . gz’ file in the same directory.

Decompress the file:

You will find that input1.txt has been compressed and it created a file input1.txt.gz in the current directory.

Example:

Execute the above code and it will create input1. txt file in the same directory.