Node.js Stream Module

Learn and memorize the Node.js Streams API with a comprehensive flashcard collection designed for developers, backend engineers, and technical interview candidates. This deck covers the complete stream ecosystem in Node.js, including Readable, Writable, Duplex, and Transform streams. Explore core concepts such as flowing and paused modes, internal buffering, highWaterMark, object mode, backpressure management, stream lifecycle events, and stream state transitions. The flashcards help you understand how to work with real-world streaming data, process large files efficiently, build scalable data pipelines, and optimize memory consumption. Topics include stream.pipe(), stream.pipeline(), stream.finished(), AbortSignal integration, async iterators, async generators, stream destruction, error handling, and Promise-based stream utilities. You'll also learn important stream events such as data, readable, end, finish, drain, pause, resume, pipe, unpipe, close, and error. Advanced topics cover Duplex and Transform streams, custom stream implementation, buffering behavior, cork/uncork operations, and performance tuning with highWaterMark settings. Whether you're preparing for a Node.js interview, improving backend engineering skills, studying system design concepts, or building production-grade applications, this flashcard set provides a structured and efficient learning path. Perfect for: • Node.js developers • Backend engineers • Full-stack developers • Technical interview preparation • Software engineering students • Teams onboarding Node.js developers Use spaced repetition to quickly memorize stream concepts, APIs, methods, properties, events, and best practices that are commonly encountered in modern Node.js applications. You may also be interested in: Master Node.js: From Basics to Production Node.js Cluster Module Node.js Child Process Module Node.js Buffer API Interview Questions Node.js Crypto Module Node.js Operating System Module Node.js File System Module

Knowledge check

Take a test before studying to see which topics you know and where the gaps are.

Take the test

Messenger lessons

Study cards and revisit what you have learned in interactive lessons.

How lessons work

Spaced repetition

Get individual cards to review at intervals that help you remember them longer.

How repetition works
Stream

A stream is an abstract interface for working with streaming data in Node.js. The node:stream module provides an API for implementing the stream interface.


There are many stream objects provided by Node.js. For instance, a request to an HTTP server and process.stdout are both stream instances.

1/79
Types of streams

There are four fundamental stream types within Node.js.


Readable: streams from which data can be read (for example, fs.createReadStream()).


Writable: streams to which data can be written (for example, fs.createWriteStream()).

2/79
Streams Promises API

The stream/promises API provides an alternative set of asynchronous utility functions for streams that return Promise objects rather than using callbacks.


The API is accessible via require('node:stream/promises') or require('node:stream').promises.

3/79
stream.pipeline

The function is a utility provided by the stream module to simplify working with streams.


It allows you to compose multiple streams into a pipeline and automatically handles errors, making it easier to manage the flow of data between streams.

4/79
AbortSignal

To use an AbortSignal, pass it inside an options object, as the last argument.


When the signal is aborted, destroy will be called on the underlying pipeline, with an AbortError.

5/79
Async generators in pipelines

pipeline() accepts async generators as sources or transforms. A transform consumes an async iterable and yields output chunks. Use the supplied signal to stop work on abort.

6/79
Abort signals in pipelines

Remember to handle the signal argument passed into the async generator.


Especially in the case where the async generator is the source for the pipeline (i.e. first argument) or the pipeline will never complete.

7/79
stream.finished

It is a utility function provided by the stream module that allows you to detect when a stream has finished reading or writing, including handling errors and other termination conditions.

8/79
Object mode

All streams created by Node.js APIs operate exclusively on strings, <Buffer>, <TypedArray> and <DataView> objects.


Strings and Buffers are the most common types used with streams.

9/79
Buffering

Both Writable and Readable streams will store data in an internal buffer.


The amount of data potentially buffered depends on the highWaterMark option passed into the stream's constructor.

10/79
API for stream consumers

Almost all Node.js applications, no matter how simple, use streams in some manner.


The following is an example of using streams in a Node.js application that implements an HTTP server.

11/79
Writable streams

Writable streams are an abstraction for a destination to which data is written.

12/79
Event: close

The 'close' event is emitted when the stream and any of its underlying resources (a file descriptor, for example) have been closed.


The event indicates that no more events will be emitted, and no further computation will occur.

13/79
Event: drain

If a call to stream.write(chunk) returns false, the 'drain' event will be emitted when it is appropriate to resume writing data to the stream.

14/79
Event: error

The 'error' event is emitted if an error occurred while writing or piping data. The listener callback is passed a single Error argument when called.


The stream is closed when the 'error' event is emitted unless the autoDestroy option was set to false when creating the stream.

15/79
Event: finish

The finish event fires after end() and all writes have been handed to the underlying system. It does not by itself prove durable storage or resource closure.

16/79
Event: pipe

src <stream.Readable> source stream that is piping to this writable


The 'pipe' event is emitted when the stream.pipe() method is called on a readable stream, adding this writable to its set of destinations.

17/79
Event: unpipe

src <stream.Readable> The source stream that unpiped this writable


The 'unpipe' event is emitted when the stream.unpipe() method is called on a Readable stream, removing this Writable from its set of destinations.

18/79
writable.cork()

The writable.cork() method forces all written data to be buffered in memory. The buffered data will be flushed when either the stream.uncork() or stream.end() methods are called.

19/79
writable.destroy([error])

error <Error> Optional, an error to emit with 'error' event.

Returns: <this>


Destroy the stream. Optionally emit an 'error' event, and emit a 'close' event (unless emitClose is set to false).

20/79
writable.closed

True after a Writable emits close. This tracks resource closure, which is distinct from the finish event and can follow an error.

21/79
writable.destroyed

True after writable.destroy() has been called. Destruction ends normal use; the close event separately signals resource closure.

22/79
writable.end()

Calling the writable.end() method signals that no more data will be written to the Writable.


The optional chunk and encoding arguments allow one final additional chunk of data to be written immediately before closing the stream.

23/79
writable.setDefaultEncoding()

Sets the default text encoding used for later string writes to a Writable. It does not re-encode chunks that were already written.

24/79
writable.uncork()

The writable.uncork() method flushes all data buffered since stream.cork() was called.

25/79
writable.writable

True while it is safe to call write() on this Writable. After end() or destruction, further writes are invalid.

26/79
writable.writableEnded

<boolean>


Is true after writable.end() has been called. This property does not indicate whether the data has been flushed, for this use writable.writableFinished instead.

27/79
writable.writableCorked

The number of uncork() calls needed to fully uncork this Writable. Each cork() increments the count; uncork() decrements it.

28/79
writable.errored

The Error that caused this Writable to fail, or null when no error was recorded. Check it alongside lifecycle state rather than treating closed as success.

29/79
writable.writableFinished

True just before the finish event fires, after end() and completion of buffered writes. It differs from writableEnded, which becomes true when end() is called.

30/79
writable.writableHighWaterMark

The highWaterMark threshold configured for the Writable. Reaching it makes write() return false; it is a backpressure threshold, not a hard memory cap.

31/79
writable.writableLength

<number>


This property contains the number of bytes (or objects) in the queue ready to be written. The value provides introspection data regarding the status of the highWaterMark.

32/79
writable.writableNeedDrain

True when a write returned false and the stream needs to emit drain before the producer resumes. Wait for drain to respect backpressure.

33/79
writable.writableObjectMode

True when the Writable operates in object mode. Its highWaterMark then counts objects rather than bytes.

34/79
writable.write()

The writable.write() method writes some data to the stream, and calls the supplied callback once the data has been fully handled. If an error occurs, the callback will be called with the error as its first argument.


The callback is called asynchronously and before 'error' is emitted.

35/79
Readable streams

Readable streams are an abstraction for a source from which data is consumed.

36/79
Two reading modes

Readable streams effectively operate in one of two modes: flowing and paused. These modes are separate from object mode.


A Readable stream can be in object mode or not, regardless of whether it is in flowing mode or paused mode.

37/79
Three states

The "two modes" of operation for a Readable stream are a simplified abstraction for the more complicated internal state management that is happening within the Readable stream implementation.

38/79
Choose one API style

The Readable stream API evolved across multiple Node.js versions and provides multiple methods of consuming stream data.


In general, developers should choose one of the methods of consuming data and should never use multiple methods to consume data from a single stream.

39/79
Event: close

The 'close' event is emitted when the stream and any of its underlying resources (a file descriptor, for example) have been closed.


The event indicates that no more events will be emitted, and no further computation will occur.

40/79
Event: data

The 'data' event is emitted whenever the stream is relinquishing ownership of a chunk of data to a consumer.


This may occur whenever the stream is switched in flowing mode by calling readable.pipe(), readable.resume(), or by attaching a listener callback to the 'data' event.

41/79
Event: end

The 'end' event is emitted when there is no more data to be consumed from the stream.


The 'end' event will not be emitted unless the data is completely consumed. This can be accomplished by switching the stream into flowing mode, or by calling stream.read() repeatedly until all data has been consumed.

42/79
Event: error

<Error>


The 'error' event may be emitted by a Readable implementation at any time. Typically, this may occur if the underlying stream is unable to generate data due to an underlying internal failure, or when a stream implementation attempts to push an invalid chunk of data.

43/79
Event: pause

The pause event reports a transition away from flowing data delivery. pause() can stop data events while keeping buffered data available for later reads.

44/79
Event: readable

The 'readable' event is emitted when there is data available to be read from the stream, up to the configured high water mark (state.highWaterMark).


Effectively, it indicates that the stream has new information within the buffer. If data is available within this buffer, stream.read() can be called to retrieve that data.

45/79
Event: resume

The resume event reports a transition back toward flowing data delivery. resume() allows data events to continue; it does not mean the stream has ended.

46/79
readable.destroy()

readable.destroy([error])


error <Error> Error which will be passed as payload in 'error' event


Returns: <this>

47/79
readable.closed

True after a Readable emits close. This tracks resource closure; end is the event that indicates no more readable data.

48/79
readable.destroyed

True after readable.destroy() has been called. The stream cannot continue normal reading, and close may be emitted afterward.

49/79
readable.isPaused()

Returns: <boolean>


The readable.isPaused() method returns the current operating state of the Readable.

50/79
readable.pause()

Returns: <this>


The readable.pause() method will cause a stream in flowing mode to stop emitting 'data' events, switching out of flowing mode. Any data that becomes available will remain in the internal buffer.

51/79
readable.pipe()

The readable.pipe() method attaches a Writable stream to the readable, causing it to switch automatically into flowing mode and push all of its data to the attached Writable.

52/79
readable.read()

The readable.read() method reads data out of the internal buffer and returns it. If no data is available to be read, null is returned.


By default, the data is returned as a Buffer object unless an encoding has been specified using the readable.setEncoding() method or the stream is operating in object mode.

53/79
readable.readable

True while it is safe to call read() on this Readable. It can become false after the stream ends or is destroyed.

54/79
readable.readableEncoding

The string encoding currently set for a Readable, or null when chunks are delivered as binary data. setEncoding() changes future decoding.

55/79
readable.readableEnded

True once the Readable has emitted end. It indicates all data has been consumed, which is distinct from resource closure.

56/79
readable.errored

The Error recorded when the Readable was destroyed by an error, or null otherwise. It helps distinguish failure from normal completion.

57/79
readable.readableFlowing

Reflects Readable flow state: null before a mode is chosen, false when paused, and true when flowing. Data listeners, pipe() and resume() can change it.

58/79
readable.readableHighWaterMark

The configured highWaterMark for this Readable. It guides internal buffering and is not a strict maximum on memory use.

59/79
readable.readableLength

<number>


This property contains the number of bytes (or objects) in the queue ready to be read. The value provides introspection data regarding the status of the highWaterMark.

60/79
readable.readableObjectMode

True when the Readable operates in object mode. In that mode, the highWaterMark counts objects rather than bytes.

61/79
readable.resume()

Returns: <this>


The readable.resume() method causes an explicitly paused Readable stream to resume emitting 'data' events, switching the stream into flowing mode.

62/79
readable.setEncoding()

The readable.setEncoding() method sets the character encoding for data read from the Readable stream.

63/79
readable.unpipe()

The readable.unpipe() method detaches a Writable stream previously attached using the stream.pipe() method.


If the destination is not specified, then all pipes are detached.


If the destination is specified, but no pipe is set up for it, then the method does nothing.

64/79
readable.unshift()

The readable.unshift() method pushes a chunk of data back into the internal buffer.


This is useful in certain situations where a stream is being consumed by code that needs to "un-consume" some amount of data that it has optimistically pulled out of the source, so that the data can be passed on to some other party.

65/79
readable.wrap(stream)

stream <Stream> An "old style" readable stream


Returns: <this>

66/79
readable [Symbol.asyncIterator]()

Returns: <AsyncIterator> to fully consume the stream.

67/79
Duplex and transform streams

Duplex streams have both readable and writable sides. Transform streams are Duplex streams whose output is derived from input; the two sides have separate lifecycle events.

68/79
duplex.allowHalfOpen

<boolean>


If false then the stream will automatically end the writable side when the readable side ends. Set initially by the allowHalfOpen constructor option, which defaults to true.

69/79
Class: stream.Transform

Transform streams are Duplex streams where the output is in some way related to the input. Like all Duplex streams, Transform streams implement both the Readable and Writable interfaces.

70/79
transform.destroy()

Destroy the stream, and optionally emit an 'error' event.

71/79
stream.duplexPair()

The utility function duplexPair returns an Array with two items, each being a Duplex stream connected to the other side.

72/79
stream.finished()

A function to get notified when a stream is no longer readable, writable or has experienced an error or a premature close event.

73/79
stream.pipeline()

A module method to pipe between streams and generators forwarding errors and properly cleaning up and provide a callback when the pipeline is complete.

74/79
stream.Readable.from()

A utility method for creating readable streams out of iterators.

75/79
stream.Duplex.from()

A utility method for creating duplex streams.

76/79
stream.addAbortSignal()

Attaches an AbortSignal to a readable or writeable stream.


This lets code control stream destruction using an AbortController.

77/79
stream.getDefaultHighWaterMark()

Returns the default highWaterMark for new streams in byte mode or object mode, selected by the boolean argument. It does not report an individual stream’s configured value.

78/79
stream.setDefaultHighWaterMark()

Changes the default highWaterMark for subsequently created streams in byte mode or object mode. Existing stream instances keep their own configured threshold.

79/79