block by joyrexus 10026630

Node.js streams demystified

A quick overview of the node.js streams interface with basic examples.

This is based on @brycebaril’s presentation, Node.js Streams2 Demystified

Overview

Streams are a first-class construct in Node.js for handling data.

Think of them as as lazy evaluation applied to data.

There are essentially three major concepts:

Benefits in using streams:

Five classes of streams:

Below is a quick overview of Readable, Writable, and Transform streams.

See also:


Readable

Use a Readable stream when supplying data as a stream.

Think: spigot/faucet.

How to implement

  1. Subclass stream.Readable.

  2. Implement a _read(size) method.

Methods

_read(size)

Options

How to use

See also


Writable

Use a Writable stream when collecting data from a stream.

Think: drain/collect.

How to implement

  1. Subclass stream.Writable.

  2. Implement a _write(chunk, encoding, callback) method.

Methods

_write(chunk, encoding, callback)

Options

How to use

See also


Transform

Use a Transform stream when you want to operate on a stream in transit. This is a special kind of Duplex stream where the input and output stream are the same stream.

Think: filter/map.

How to implement

  1. Subclass stream.Transform.
  2. Implement a _transform(chunk, encoding, callback) method.
  3. Optionally implement a _flush(callback) method.

Methods

_transform(chunk, encoding, callback)

Call this.push(something) to forward it to the next consumer. You don’t have to push anything, this will skip a chunk. You must call callback one time per _transform call.

_flush(callback)

When the stream ends, this is your chance to do any cleanup or last-minute this.push() calls to clear any buffers or work. Call callback() when done.

Options

Superset of Readable and Writable options.

How to use

See also

readable.coffee

readable.js

transform.coffee

transform.js

writable.coffee

writable.js