CodePark/ questions / Streams & backpressure
START PRACTICINGPRACTICE
Backend question · Node.js › Streams & backpressure

What are streams in Node.js, and what are the four types?

A stream handles data piece by piece, instead of loading all of it into memory at once. Each piece is called a chunk.

This helps in two ways:

  • Memory use stays flat, even for large files or large network bodies.
  • You can start working before all the data has arrived.

There are four types:

  • Readable streams are sources of data. Examples: fs.createReadStream or an incoming HTTP request.
  • Writable streams are destinations for data. Examples: fs.createWriteStream or an HTTP response.
  • Duplex streams are both readable and writable. The read side and the write side are independent. Example: a TCP socket.
  • Transform streams are duplex streams where the output is calculated from the input. Examples: zlib.createGzip() or a cipher.

All streams are EventEmitters (objects that emit named events you can listen to). By default, chunks are Buffer objects or strings. In object mode, a stream can carry any JavaScript value.

  • Streams process data in chunks, so memory use stays bounded.
  • The four types are Readable, Writable, Duplex and Transform.
  • Examples include fs streams, HTTP request and response, sockets and zlib.
  • Streams are EventEmitters, and object mode lets them carry any value.