Sobes.tech
Junior — Middle

What is the application of data streams in Node.js?

sobes.tech AI

Answer from AI

Streams in Node.js are used for efficient processing of large volumes of data without the need to load them entirely into memory. This is especially important when working with files, network requests, and other data sources.

Main applications of streams:

  • Reading and writing files: data can be read or written in parts, saving memory.
  • Processing HTTP requests and responses: data is transmitted and processed as it arrives.
  • Pipelines (pipe): allow chaining multiple streams for sequential data processing.

Example of reading a file using a stream:

const fs = require('fs');
const readStream = fs.createReadStream('file.txt', 'utf8');

readStream.on('data', chunk => {
  console.log('Received fragment:', chunk);
});

readStream.on('end', () => {
  console.log('File reading completed');
});

Thus, streams enable efficient and asynchronous data processing.