Sobes.tech
Junior — Middle

Can you explain what a data stream (Stream) is in Node.js and how it is used?

sobes.tech AI

Answer from AI

In Node.js, a stream is an abstraction for working with sequential data that arrives or is sent in parts rather than all at once. This allows efficient processing of large volumes of data without the need to load them entirely into memory.

There are four main types of streams:

  • Readable — streams from which data can be read (e.g., reading a file).
  • Writable — streams to which data can be written (e.g., writing to a file).
  • Duplex — streams that can both read and write (e.g., network sockets).
  • Transform — a type of Duplex that can modify data as it passes through (e.g., compression).

Example of using a readable stream to read a file and write its contents to another file:

const fs = require('fs');

const readable = fs.createReadStream('input.txt');
const writable = fs.createWriteStream('output.txt');

readable.pipe(writable);

The pipe() method automatically transfers data from one stream to another, simplifying stream handling and increasing performance when processing large data.

Can you explain what a data stream (Stream) is in… - sobes.tech