nodejs
  1. nodejs-streams

Node.js Streams

In Node.js, streams are an important concept that provide a mechanism for reading and writing data in an efficient and scalable manner. In this tutorial, we'll discuss how to use streams in Node.js.

Syntax

Streams in Node.js are implemented as objects containing two primary modes of operation:

  1. Readable – used to read input data from a source.
  2. Writable – used to write output data to a destination.

Here's an example of a simple stream that reads input data from a source and writes it to a destination:

const { Readable, Writable } = require('stream');

const readStream = new Readable({
  read(size) {
    let data = "Hello, World!";
    this.push(data);
    this.push(null);
  }
});

const writeStream = new Writable({
  write(chunk, encoding, callback) {
    console.log(chunk.toString());
    callback();
  }
});

readStream.pipe(writeStream);

Example

In this example, we're creating a Readable stream that pushes the string "Hello, World!" into the stream. We're also creating a Writable stream that logs the data to the console.

Then, we're using the pipe method to connect the two streams. This sends the data from the readStream to the writeStream.

When we run this code, it will simply output "Hello, World!" to the console.

Output

When the above code is executed, the output will be:

Hello, World!

Explanation

In the above example, we created a Readable stream that pushes the string "Hello, World!" into the stream. We also created a Writable stream that logs the data to the console.

We then used the pipe method to connect the two streams. This sends the data from the readStream to the writeStream.

When we ran this code, it output "Hello, World!" to the console.

Use

Streams are useful when you need to process data in real-time, especially in situations where you may have to work with large amounts of data. Streams are efficient, as they allow you to read and write data in chunks, rather than all at once.

In Node.js, streams are used in several scenarios, such as HTTP requests and responses, file system operations, and database access.

Important Points

  • Streams are an important concept in Node.js, providing a mechanism for reading and writing data in an efficient and scalable manner.
  • Streams come in two primary modes of operation: readable and writable.
  • Streams have a mechanism for piping data from one stream to another, which can enable efficient processing of data.

Summary

In this tutorial, we discussed how to use streams in Node.js. We covered the syntax, example, output, explanation, use, and important points of streams in Node.js. With this knowledge, you can now leverage streams in your Node.js applications to read and write data in real-time.

Published on: