Source Code: lib/stream.js
A stream is an abstract interface for working with streaming data in Node.js.\nThe node:stream module provides an API for implementing the stream interface.
node:stream
There are many stream objects provided by Node.js. For instance, a\nrequest to an HTTP server and process.stdout\nare both stream instances.
process.stdout
Streams can be readable, writable, or both. All streams are instances of\nEventEmitter.
EventEmitter
To access the node:stream module:
const stream = require('node:stream');\n
The node:stream module is useful for creating new types of stream instances.\nIt is usually not necessary to use the node:stream module to consume streams.
This document contains two primary sections and a third section for notes. The\nfirst section explains how to use existing streams within an application. The\nsecond section explains how to create new types of streams.
There are four fundamental stream types within Node.js:
Writable
fs.createWriteStream()
Readable
fs.createReadStream()
Duplex
net.Socket
Transform
zlib.createDeflate()
Additionally, this module includes the utility functions\nstream.pipeline(), stream.finished(), stream.Readable.from()\nand stream.addAbortSignal().
stream.pipeline()
stream.finished()
stream.Readable.from()
stream.addAbortSignal()
The stream/promises API provides an alternative set of asynchronous utility\nfunctions for streams that return Promise objects rather than using\ncallbacks. The API is accessible via require('node:stream/promises')\nor require('node:stream').promises.
stream/promises
Promise
require('node:stream/promises')
require('node:stream').promises
All streams created by Node.js APIs operate exclusively on strings and Buffer\n(or Uint8Array) objects. It is possible, however, for stream implementations\nto work with other types of JavaScript values (with the exception of null,\nwhich serves a special purpose within streams). Such streams are considered to\noperate in \"object mode\".
Buffer
Uint8Array
null
Stream instances are switched into object mode using the objectMode option\nwhen the stream is created. Attempting to switch an existing stream into\nobject mode is not safe.
objectMode
Both Writable and Readable streams will store data in an internal\nbuffer.
The amount of data potentially buffered depends on the highWaterMark option\npassed into the stream's constructor. For normal streams, the highWaterMark\noption specifies a total number of bytes. For streams operating\nin object mode, the highWaterMark specifies a total number of objects.
highWaterMark
Data is buffered in Readable streams when the implementation calls\nstream.push(chunk). If the consumer of the Stream does not\ncall stream.read(), the data will sit in the internal\nqueue until it is consumed.
stream.push(chunk)
stream.read()
Once the total size of the internal read buffer reaches the threshold specified\nby highWaterMark, the stream will temporarily stop reading data from the\nunderlying resource until the data currently buffered can be consumed (that is,\nthe stream will stop calling the internal readable._read() method that is\nused to fill the read buffer).
readable._read()
Data is buffered in Writable streams when the\nwritable.write(chunk) method is called repeatedly. While the\ntotal size of the internal write buffer is below the threshold set by\nhighWaterMark, calls to writable.write() will return true. Once\nthe size of the internal buffer reaches or exceeds the highWaterMark, false\nwill be returned.
writable.write(chunk)
writable.write()
true
false
A key goal of the stream API, particularly the stream.pipe() method,\nis to limit the buffering of data to acceptable levels such that sources and\ndestinations of differing speeds will not overwhelm the available memory.
stream
stream.pipe()
The highWaterMark option is a threshold, not a limit: it dictates the amount\nof data that a stream buffers before it stops asking for more data. It does not\nenforce a strict memory limitation in general. Specific stream implementations\nmay choose to enforce stricter limits but doing so is optional.
Because Duplex and Transform streams are both Readable and\nWritable, each maintains two separate internal buffers used for reading and\nwriting, allowing each side to operate independently of the other while\nmaintaining an appropriate and efficient flow of data. For example,\nnet.Socket instances are Duplex streams whose Readable side allows\nconsumption of data received from the socket and whose Writable side allows\nwriting data to the socket. Because data may be written to the socket at a\nfaster or slower rate than data is received, each side should\noperate (and buffer) independently of the other.
The mechanics of the internal buffering are an internal implementation detail\nand may be changed at any time. However, for certain advanced implementations,\nthe internal buffers can be retrieved using writable.writableBuffer or\nreadable.readableBuffer. Use of these undocumented properties is discouraged.
writable.writableBuffer
readable.readableBuffer
A function to get notified when a stream is no longer readable, writable\nor has experienced an error or a premature close event.
const { finished } = require('node:stream');\nconst fs = require('node:fs');\n\nconst rs = fs.createReadStream('archive.tar');\n\nfinished(rs, (err) => {\n if (err) {\n console.error('Stream failed.', err);\n } else {\n console.log('Stream is done reading.');\n }\n});\n\nrs.resume(); // Drain the stream.\n
Especially useful in error handling scenarios where a stream is destroyed\nprematurely (like an aborted HTTP request), and will not emit 'end'\nor 'finish'.
'end'
'finish'
The finished API provides promise version:
finished
const { finished } = require('node:stream/promises');\nconst fs = require('node:fs');\n\nconst rs = fs.createReadStream('archive.tar');\n\nasync function run() {\n await finished(rs);\n console.log('Stream is done reading.');\n}\n\nrun().catch(console.error);\nrs.resume(); // Drain the stream.\n
stream.finished() leaves dangling event listeners (in particular\n'error', 'end', 'finish' and 'close') after callback has been\ninvoked. The reason for this is so that unexpected 'error' events (due to\nincorrect stream implementations) do not cause unexpected crashes.\nIf this is unwanted behavior then the returned cleanup function needs to be\ninvoked in the callback:
'error'
'close'
callback
const cleanup = finished(rs, (err) => {\n cleanup();\n // ...\n});\n
A module method to pipe between streams and generators forwarding errors and\nproperly cleaning up and provide a callback when the pipeline is complete.
const { pipeline } = require('node:stream');\nconst fs = require('node:fs');\nconst zlib = require('node:zlib');\n\n// Use the pipeline API to easily pipe a series of streams\n// together and get notified when the pipeline is fully done.\n\n// A pipeline to gzip a potentially huge tar file efficiently:\n\npipeline(\n fs.createReadStream('archive.tar'),\n zlib.createGzip(),\n fs.createWriteStream('archive.tar.gz'),\n (err) => {\n if (err) {\n console.error('Pipeline failed.', err);\n } else {\n console.log('Pipeline succeeded.');\n }\n }\n);\n
The pipeline API provides a promise version, which can also\nreceive an options argument as the last parameter with a\nsignal <AbortSignal> property. When the signal is aborted,\ndestroy will be called on the underlying pipeline, with an\nAbortError.
pipeline
signal
destroy
AbortError
const { pipeline } = require('node:stream/promises');\nconst fs = require('node:fs');\nconst zlib = require('node:zlib');\n\nasync function run() {\n await pipeline(\n fs.createReadStream('archive.tar'),\n zlib.createGzip(),\n fs.createWriteStream('archive.tar.gz')\n );\n console.log('Pipeline succeeded.');\n}\n\nrun().catch(console.error);\n
To use an AbortSignal, pass it inside an options object,\nas the last argument:
AbortSignal
const { pipeline } = require('node:stream/promises');\nconst fs = require('node:fs');\nconst zlib = require('node:zlib');\n\nasync function run() {\n const ac = new AbortController();\n const signal = ac.signal;\n\n setTimeout(() => ac.abort(), 1);\n await pipeline(\n fs.createReadStream('archive.tar'),\n zlib.createGzip(),\n fs.createWriteStream('archive.tar.gz'),\n { signal },\n );\n}\n\nrun().catch(console.error); // AbortError\n
The pipeline API also supports async generators:
const { pipeline } = require('node:stream/promises');\nconst fs = require('node:fs');\n\nasync function run() {\n await pipeline(\n fs.createReadStream('lowercase.txt'),\n async function* (source, { signal }) {\n source.setEncoding('utf8'); // Work with strings rather than `Buffer`s.\n for await (const chunk of source) {\n yield await processChunk(chunk, { signal });\n }\n },\n fs.createWriteStream('uppercase.txt')\n );\n console.log('Pipeline succeeded.');\n}\n\nrun().catch(console.error);\n
Remember to handle the signal argument passed into the async generator.\nEspecially in the case where the async generator is the source for the\npipeline (i.e. first argument) or the pipeline will never complete.
const { pipeline } = require('node:stream/promises');\nconst fs = require('node:fs');\n\nasync function run() {\n await pipeline(\n async function* ({ signal }) {\n await someLongRunningfn({ signal });\n yield 'asd';\n },\n fs.createWriteStream('uppercase.txt')\n );\n console.log('Pipeline succeeded.');\n}\n\nrun().catch(console.error);\n
stream.pipeline() will call stream.destroy(err) on all streams except:
stream.destroy(err)
stream.pipeline() leaves dangling event listeners on the streams\nafter the callback has been invoked. In the case of reuse of streams after\nfailure, this can cause event listener leaks and swallowed errors.
stream.pipeline() closes all the streams when an error is raised.\nThe IncomingRequest usage with pipeline could lead to an unexpected behavior\nonce it would destroy the socket without sending the expected response.\nSee the example below:
IncomingRequest
const fs = require('node:fs');\nconst http = require('node:http');\nconst { pipeline } = require('node:stream');\n\nconst server = http.createServer((req, res) => {\n const fileStream = fs.createReadStream('./fileNotExist.txt');\n pipeline(fileStream, res, (err) => {\n if (err) {\n console.log(err); // No such file\n // this message can't be sent once `pipeline` already destroyed the socket\n return res.end('error!!!');\n }\n });\n});\n
Combines two or more streams into a Duplex stream that writes to the\nfirst stream and reads from the last. Each provided stream is piped into\nthe next, using stream.pipeline. If any of the streams error then all\nare destroyed, including the outer Duplex stream.
stream.pipeline
Because stream.compose returns a new stream that in turn can (and\nshould) be piped into other streams, it enables composition. In contrast,\nwhen passing streams to stream.pipeline, typically the first stream is\na readable stream and the last a writable stream, forming a closed\ncircuit.
stream.compose
If passed a Function it must be a factory method taking a source\nIterable.
Function
source
Iterable
import { compose, Transform } from 'node:stream';\n\nconst removeSpaces = new Transform({\n transform(chunk, encoding, callback) {\n callback(null, String(chunk).replace(' ', ''));\n }\n});\n\nasync function* toUpper(source) {\n for await (const chunk of source) {\n yield String(chunk).toUpperCase();\n }\n}\n\nlet res = '';\nfor await (const buf of compose(removeSpaces, toUpper).end('hello world')) {\n res += buf;\n}\n\nconsole.log(res); // prints 'HELLOWORLD'\n
stream.compose can be used to convert async iterables, generators and\nfunctions into streams.
AsyncIterable
AsyncGeneratorFunction
AsyncFunction
undefined
import { compose } from 'node:stream';\nimport { finished } from 'node:stream/promises';\n\n// Convert AsyncIterable into readable Duplex.\nconst s1 = compose(async function*() {\n yield 'Hello';\n yield 'World';\n}());\n\n// Convert AsyncGenerator into transform Duplex.\nconst s2 = compose(async function*(source) {\n for await (const chunk of source) {\n yield String(chunk).toUpperCase();\n }\n});\n\nlet res = '';\n\n// Convert AsyncFunction into writable Duplex.\nconst s3 = compose(async function(source) {\n for await (const chunk of source) {\n res += chunk;\n }\n});\n\nawait finished(compose(s1, s2, s3));\n\nconsole.log(res); // prints 'HELLOWORLD'\n
A utility method for creating readable streams out of iterators.
const { Readable } = require('node:stream');\n\nasync function * generate() {\n yield 'hello';\n yield 'streams';\n}\n\nconst readable = Readable.from(generate());\n\nreadable.on('data', (chunk) => {\n console.log(chunk);\n});\n
Calling Readable.from(string) or Readable.from(buffer) will not have\nthe strings or buffers be iterated to match the other streams semantics\nfor performance reasons.
Readable.from(string)
Readable.from(buffer)
Returns whether the stream has been read from or cancelled.
Returns whether the stream has encountered an error.
Returns whether the stream is readable.
A utility method for creating duplex streams.
Stream
Blob
string
ArrayBuffer
Object ({ writable, readable })
readable
writable
Attaches an AbortSignal to a readable or writeable stream. This lets code\ncontrol stream destruction using an AbortController.
AbortController
Calling abort on the AbortController corresponding to the passed\nAbortSignal will behave the same way as calling .destroy(new AbortError())\non the stream.
abort
.destroy(new AbortError())
const fs = require('node:fs');\n\nconst controller = new AbortController();\nconst read = addAbortSignal(\n controller.signal,\n fs.createReadStream(('object.json'))\n);\n// Later, abort the operation closing the stream\ncontroller.abort();\n
Or using an AbortSignal with a readable stream as an async iterable:
const controller = new AbortController();\nsetTimeout(() => controller.abort(), 10_000); // set a timeout\nconst stream = addAbortSignal(\n controller.signal,\n fs.createReadStream(('object.json'))\n);\n(async () => {\n try {\n for await (const chunk of stream) {\n await process(chunk);\n }\n } catch (e) {\n if (e.name === 'AbortError') {\n // The operation was cancelled\n } else {\n throw e;\n }\n }\n})();\n
There are some cases where it is necessary to trigger a refresh of the\nunderlying readable stream mechanisms, without actually consuming any\ndata. In such cases, it is possible to call readable.read(0), which will\nalways return null.
readable.read(0)
If the internal read buffer is below the highWaterMark, and the\nstream is not currently reading, then calling stream.read(0) will trigger\na low-level stream._read() call.
stream.read(0)
stream._read()
While most applications will almost never need to do this, there are\nsituations within Node.js where this is done, particularly in the\nReadable stream class internals.
Use of readable.push('') is not recommended.
readable.push('')
Pushing a zero-byte string, Buffer, or Uint8Array to a stream that is not in\nobject mode has an interesting side effect. Because it is a call to\nreadable.push(), the call will end the reading process.\nHowever, because the argument is an empty string, no data is added to the\nreadable buffer so there is nothing for a user to consume.
readable.push()
Almost all Node.js applications, no matter how simple, use streams in some\nmanner. The following is an example of using streams in a Node.js application\nthat implements an HTTP server:
const http = require('node:http');\n\nconst server = http.createServer((req, res) => {\n // `req` is an http.IncomingMessage, which is a readable stream.\n // `res` is an http.ServerResponse, which is a writable stream.\n\n let body = '';\n // Get the data as utf8 strings.\n // If an encoding is not set, Buffer objects will be received.\n req.setEncoding('utf8');\n\n // Readable streams emit 'data' events once a listener is added.\n req.on('data', (chunk) => {\n body += chunk;\n });\n\n // The 'end' event indicates that the entire body has been received.\n req.on('end', () => {\n try {\n const data = JSON.parse(body);\n // Write back something interesting to the user:\n res.write(typeof data);\n res.end();\n } catch (er) {\n // uh oh! bad json!\n res.statusCode = 400;\n return res.end(`error: ${er.message}`);\n }\n });\n});\n\nserver.listen(1337);\n\n// $ curl localhost:1337 -d \"{}\"\n// object\n// $ curl localhost:1337 -d \"\\\"foo\\\"\"\n// string\n// $ curl localhost:1337 -d \"not json\"\n// error: Unexpected token o in JSON at position 1\n
Writable streams (such as res in the example) expose methods such as\nwrite() and end() that are used to write data onto the stream.
res
write()
end()
Readable streams use the EventEmitter API for notifying application\ncode when data is available to be read off the stream. That available data can\nbe read from the stream in multiple ways.
Both Writable and Readable streams use the EventEmitter API in\nvarious ways to communicate the current state of the stream.
Duplex and Transform streams are both Writable and\nReadable.
Applications that are either writing data to or consuming data from a stream\nare not required to implement the stream interfaces directly and will generally\nhave no reason to call require('node:stream').
require('node:stream')
Developers wishing to implement new types of streams should refer to the\nsection API for stream implementers.
Writable streams are an abstraction for a destination to which data is\nwritten.
Examples of Writable streams include:
process.stderr
Some of these examples are actually Duplex streams that implement the\nWritable interface.
All Writable streams implement the interface defined by the\nstream.Writable class.
stream.Writable
While specific instances of Writable streams may differ in various ways,\nall Writable streams follow the same fundamental usage pattern as illustrated\nin the example below:
const myStream = getWritableStreamSomehow();\nmyStream.write('some data');\nmyStream.write('some more data');\nmyStream.end('done writing data');\n
The 'close' event is emitted when the stream and any of its underlying\nresources (a file descriptor, for example) have been closed. The event indicates\nthat no more events will be emitted, and no further computation will occur.
A Writable stream will always emit the 'close' event if it is\ncreated with the emitClose option.
emitClose
If a call to stream.write(chunk) returns false, the\n'drain' event will be emitted when it is appropriate to resume writing data\nto the stream.
stream.write(chunk)
'drain'
// Write the data to the supplied writable stream one million times.\n// Be attentive to back-pressure.\nfunction writeOneMillionTimes(writer, data, encoding, callback) {\n let i = 1000000;\n write();\n function write() {\n let ok = true;\n do {\n i--;\n if (i === 0) {\n // Last time!\n writer.write(data, encoding, callback);\n } else {\n // See if we should continue, or wait.\n // Don't pass the callback, because we're not done yet.\n ok = writer.write(data, encoding);\n }\n } while (i > 0 && ok);\n if (i > 0) {\n // Had to stop early!\n // Write some more once it drains.\n writer.once('drain', write);\n }\n }\n}\n
The 'error' event is emitted if an error occurred while writing or piping\ndata. The listener callback is passed a single Error argument when called.
Error
The stream is closed when the 'error' event is emitted unless the\nautoDestroy option was set to false when creating the\nstream.
autoDestroy
After 'error', no further events other than 'close' should be emitted\n(including 'error' events).
The 'finish' event is emitted after the stream.end() method\nhas been called, and all data has been flushed to the underlying system.
stream.end()
const writer = getWritableStreamSomehow();\nfor (let i = 0; i < 100; i++) {\n writer.write(`hello, #${i}!\\n`);\n}\nwriter.on('finish', () => {\n console.log('All writes are now complete.');\n});\nwriter.end('This is the end\\n');\n
The 'pipe' event is emitted when the stream.pipe() method is called on\na readable stream, adding this writable to its set of destinations.
'pipe'
const writer = getWritableStreamSomehow();\nconst reader = getReadableStreamSomehow();\nwriter.on('pipe', (src) => {\n console.log('Something is piping into the writer.');\n assert.equal(src, reader);\n});\nreader.pipe(writer);\n
The 'unpipe' event is emitted when the stream.unpipe() method is called\non a Readable stream, removing this Writable from its set of\ndestinations.
'unpipe'
stream.unpipe()
This is also emitted in case this Writable stream emits an error when a\nReadable stream pipes into it.
const writer = getWritableStreamSomehow();\nconst reader = getReadableStreamSomehow();\nwriter.on('unpipe', (src) => {\n console.log('Something has stopped piping into the writer.');\n assert.equal(src, reader);\n});\nreader.pipe(writer);\nreader.unpipe(writer);\n
The writable.cork() method forces all written data to be buffered in memory.\nThe buffered data will be flushed when either the stream.uncork() or\nstream.end() methods are called.
writable.cork()
stream.uncork()
The primary intent of writable.cork() is to accommodate a situation in which\nseveral small chunks are written to the stream in rapid succession. Instead of\nimmediately forwarding them to the underlying destination, writable.cork()\nbuffers all the chunks until writable.uncork() is called, which will pass them\nall to writable._writev(), if present. This prevents a head-of-line blocking\nsituation where data is being buffered while waiting for the first small chunk\nto be processed. However, use of writable.cork() without implementing\nwritable._writev() may have an adverse effect on throughput.
writable.uncork()
writable._writev()
See also: writable.uncork(), writable._writev().
Destroy the stream. Optionally emit an 'error' event, and emit a 'close'\nevent (unless emitClose is set to false). After this call, the writable\nstream has ended and subsequent calls to write() or end() will result in\nan ERR_STREAM_DESTROYED error.\nThis is a destructive and immediate way to destroy a stream. Previous calls to\nwrite() may not have drained, and may trigger an ERR_STREAM_DESTROYED error.\nUse end() instead of destroy if data should flush before close, or wait for\nthe 'drain' event before destroying the stream.
ERR_STREAM_DESTROYED
const { Writable } = require('node:stream');\n\nconst myStream = new Writable();\n\nconst fooErr = new Error('foo error');\nmyStream.destroy(fooErr);\nmyStream.on('error', (fooErr) => console.error(fooErr.message)); // foo error\n
const { Writable } = require('node:stream');\n\nconst myStream = new Writable();\n\nmyStream.destroy();\nmyStream.on('error', function wontHappen() {});\n
const { Writable } = require('node:stream');\n\nconst myStream = new Writable();\nmyStream.destroy();\n\nmyStream.write('foo', (error) => console.error(error.code));\n// ERR_STREAM_DESTROYED\n
Once destroy() has been called any further calls will be a no-op and no\nfurther errors except from _destroy() may be emitted as 'error'.
destroy()
_destroy()
Implementors should not override this method,\nbut instead implement writable._destroy().
writable._destroy()
Calling the writable.end() method signals that no more data will be written\nto the Writable. The optional chunk and encoding arguments allow one\nfinal additional chunk of data to be written immediately before closing the\nstream.
writable.end()
chunk
encoding
Calling the stream.write() method after calling\nstream.end() will raise an error.
stream.write()
// Write 'hello, ' and then end with 'world!'.\nconst fs = require('node:fs');\nconst file = fs.createWriteStream('example.txt');\nfile.write('hello, ');\nfile.end('world!');\n// Writing more now is not allowed!\n
The writable.setDefaultEncoding() method sets the default encoding for a\nWritable stream.
writable.setDefaultEncoding()
The writable.uncork() method flushes all data buffered since\nstream.cork() was called.
stream.cork()
When using writable.cork() and writable.uncork() to manage the buffering\nof writes to a stream, defer calls to writable.uncork() using\nprocess.nextTick(). Doing so allows batching of all\nwritable.write() calls that occur within a given Node.js event loop phase.
process.nextTick()
stream.cork();\nstream.write('some ');\nstream.write('data ');\nprocess.nextTick(() => stream.uncork());\n
If the writable.cork() method is called multiple times on a stream, the\nsame number of calls to writable.uncork() must be called to flush the buffered\ndata.
stream.cork();\nstream.write('some ');\nstream.cork();\nstream.write('data ');\nprocess.nextTick(() => {\n stream.uncork();\n // The data will not be flushed until uncork() is called a second time.\n stream.uncork();\n});\n
See also: writable.cork().
The writable.write() method writes some data to the stream, and calls the\nsupplied callback once the data has been fully handled. If an error\noccurs, the callback will be called with the error as its\nfirst argument. The callback is called asynchronously and before 'error' is\nemitted.
The return value is true if the internal buffer is less than the\nhighWaterMark configured when the stream was created after admitting chunk.\nIf false is returned, further attempts to write data to the stream should\nstop until the 'drain' event is emitted.
While a stream is not draining, calls to write() will buffer chunk, and\nreturn false. Once all currently buffered chunks are drained (accepted for\ndelivery by the operating system), the 'drain' event will be emitted.\nOnce write() returns false, do not write more chunks\nuntil the 'drain' event is emitted. While calling write() on a stream that\nis not draining is allowed, Node.js will buffer all written chunks until\nmaximum memory usage occurs, at which point it will abort unconditionally.\nEven before it aborts, high memory usage will cause poor garbage collector\nperformance and high RSS (which is not typically released back to the system,\neven after the memory is no longer required). Since TCP sockets may never\ndrain if the remote peer does not read the data, writing a socket that is\nnot draining may lead to a remotely exploitable vulnerability.
Writing data while the stream is not draining is particularly\nproblematic for a Transform, because the Transform streams are paused\nby default until they are piped or a 'data' or 'readable' event handler\nis added.
'data'
'readable'
If the data to be written can be generated or fetched on demand, it is\nrecommended to encapsulate the logic into a Readable and use\nstream.pipe(). However, if calling write() is preferred, it is\npossible to respect backpressure and avoid memory issues using the\n'drain' event:
function write(data, cb) {\n if (!stream.write(data)) {\n stream.once('drain', cb);\n } else {\n process.nextTick(cb);\n }\n}\n\n// Wait for cb to be called before doing any other write.\nwrite('hello', () => {\n console.log('Write completed, do more writes now.');\n});\n
A Writable stream in object mode will always ignore the encoding argument.
Is true after writable.destroy() has been called.
writable.destroy()
const { Writable } = require('node:stream');\n\nconst myStream = new Writable();\n\nconsole.log(myStream.destroyed); // false\nmyStream.destroy();\nconsole.log(myStream.destroyed); // true\n
Is true if it is safe to call writable.write(), which means\nthe stream has not been destroyed, errored, or ended.
Returns whether the stream was destroyed or errored before emitting 'finish'.
Is true after writable.end() has been called. This property\ndoes not indicate whether the data has been flushed, for this use\nwritable.writableFinished instead.
writable.writableFinished
Number of times writable.uncork() needs to be\ncalled in order to fully uncork the stream.
Is set to true immediately before the 'finish' event is emitted.
Return the value of highWaterMark passed when creating this Writable.
This property contains the number of bytes (or objects) in the queue\nready to be written. The value provides introspection data regarding\nthe status of the highWaterMark.
Is true if the stream's buffer has been full and stream will emit 'drain'.
Getter for the property objectMode of a given Writable stream.
Readable streams are an abstraction for a source from which data is\nconsumed.
Examples of Readable streams include:
process.stdin
All Readable streams implement the interface defined by the\nstream.Readable class.
stream.Readable
Readable streams effectively operate in one of two modes: flowing and\npaused. These modes are separate from object mode.\nA Readable stream can be in object mode or not, regardless of whether\nit is in flowing mode or paused mode.
In flowing mode, data is read from the underlying system automatically\nand provided to an application as quickly as possible using events via the\nEventEmitter interface.
In paused mode, the stream.read() method must be called\nexplicitly to read chunks of data from the stream.
All Readable streams begin in paused mode but can be switched to flowing\nmode in one of the following ways:
stream.resume()
The Readable can switch back to paused mode using one of the following:
stream.pause()
The important concept to remember is that a Readable will not generate data\nuntil a mechanism for either consuming or ignoring that data is provided. If\nthe consuming mechanism is disabled or taken away, the Readable will attempt\nto stop generating the data.
For backward compatibility reasons, removing 'data' event handlers will\nnot automatically pause the stream. Also, if there are piped destinations,\nthen calling stream.pause() will not guarantee that the\nstream will remain paused once those destinations drain and ask for more data.
If a Readable is switched into flowing mode and there are no consumers\navailable to handle the data, that data will be lost. This can occur, for\ninstance, when the readable.resume() method is called without a listener\nattached to the 'data' event, or when a 'data' event handler is removed\nfrom the stream.
readable.resume()
Adding a 'readable' event handler automatically makes the stream\nstop flowing, and the data has to be consumed via\nreadable.read(). If the 'readable' event handler is\nremoved, then the stream will start flowing again if there is a\n'data' event handler.
readable.read()
The \"two modes\" of operation for a Readable stream are a simplified\nabstraction for the more complicated internal state management that is happening\nwithin the Readable stream implementation.
Specifically, at any given point in time, every Readable is in one of three\npossible states:
readable.readableFlowing === null
readable.readableFlowing === false
readable.readableFlowing === true
When readable.readableFlowing is null, no mechanism for consuming the\nstream's data is provided. Therefore, the stream will not generate data.\nWhile in this state, attaching a listener for the 'data' event, calling the\nreadable.pipe() method, or calling the readable.resume() method will switch\nreadable.readableFlowing to true, causing the Readable to begin actively\nemitting events as data is generated.
readable.readableFlowing
readable.pipe()
Calling readable.pause(), readable.unpipe(), or receiving backpressure\nwill cause the readable.readableFlowing to be set as false,\ntemporarily halting the flowing of events but not halting the generation of\ndata. While in this state, attaching a listener for the 'data' event\nwill not switch readable.readableFlowing to true.
readable.pause()
readable.unpipe()
const { PassThrough, Writable } = require('node:stream');\nconst pass = new PassThrough();\nconst writable = new Writable();\n\npass.pipe(writable);\npass.unpipe(writable);\n// readableFlowing is now false.\n\npass.on('data', (chunk) => { console.log(chunk.toString()); });\npass.write('ok'); // Will not emit 'data'.\npass.resume(); // Must be called to make stream emit 'data'.\n
While readable.readableFlowing is false, data may be accumulating\nwithin the stream's internal buffer.
The Readable stream API evolved across multiple Node.js versions and provides\nmultiple methods of consuming stream data. In general, developers should choose\none of the methods of consuming data and should never use multiple methods\nto consume data from a single stream. Specifically, using a combination\nof on('data'), on('readable'), pipe(), or async iterators could\nlead to unintuitive behavior.
on('data')
on('readable')
pipe()
A Readable stream will always emit the 'close' event if it is\ncreated with the emitClose option.
The 'data' event is emitted whenever the stream is relinquishing ownership of\na chunk of data to a consumer. This may occur whenever the stream is switched\nin flowing mode by calling readable.pipe(), readable.resume(), or by\nattaching a listener callback to the 'data' event. The 'data' event will\nalso be emitted whenever the readable.read() method is called and a chunk of\ndata is available to be returned.
Attaching a 'data' event listener to a stream that has not been explicitly\npaused will switch the stream into flowing mode. Data will then be passed as\nsoon as it is available.
The listener callback will be passed the chunk of data as a string if a default\nencoding has been specified for the stream using the\nreadable.setEncoding() method; otherwise the data will be passed as a\nBuffer.
readable.setEncoding()
const readable = getReadableStreamSomehow();\nreadable.on('data', (chunk) => {\n console.log(`Received ${chunk.length} bytes of data.`);\n});\n
The 'end' event is emitted when there is no more data to be consumed from\nthe stream.
The 'end' event will not be emitted unless the data is completely\nconsumed. This can be accomplished by switching the stream into flowing mode,\nor by calling stream.read() repeatedly until all data has been\nconsumed.
const readable = getReadableStreamSomehow();\nreadable.on('data', (chunk) => {\n console.log(`Received ${chunk.length} bytes of data.`);\n});\nreadable.on('end', () => {\n console.log('There will be no more data.');\n});\n
The 'error' event may be emitted by a Readable implementation at any time.\nTypically, this may occur if the underlying stream is unable to generate data\ndue to an underlying internal failure, or when a stream implementation attempts\nto push an invalid chunk of data.
The listener callback will be passed a single Error object.
The 'pause' event is emitted when stream.pause() is called\nand readableFlowing is not false.
'pause'
readableFlowing
The 'readable' event is emitted when there is data available to be read from\nthe stream or when the end of the stream has been reached. Effectively, the\n'readable' event indicates that the stream has new information. If data is\navailable, stream.read() will return that data.
const readable = getReadableStreamSomehow();\nreadable.on('readable', function() {\n // There is some data to read now.\n let data;\n\n while ((data = this.read()) !== null) {\n console.log(data);\n }\n});\n
If the end of the stream has been reached, calling\nstream.read() will return null and trigger the 'end'\nevent. This is also true if there never was any data to be read. For instance,\nin the following example, foo.txt is an empty file:
foo.txt
const fs = require('node:fs');\nconst rr = fs.createReadStream('foo.txt');\nrr.on('readable', () => {\n console.log(`readable: ${rr.read()}`);\n});\nrr.on('end', () => {\n console.log('end');\n});\n
The output of running this script is:
$ node test.js\nreadable: null\nend\n
In some cases, attaching a listener for the 'readable' event will cause some\namount of data to be read into an internal buffer.
In general, the readable.pipe() and 'data' event mechanisms are easier to\nunderstand than the 'readable' event. However, handling 'readable' might\nresult in increased throughput.
If both 'readable' and 'data' are used at the same time, 'readable'\ntakes precedence in controlling the flow, i.e. 'data' will be emitted\nonly when stream.read() is called. The\nreadableFlowing property would become false.\nIf there are 'data' listeners when 'readable' is removed, the stream\nwill start flowing, i.e. 'data' events will be emitted without calling\n.resume().
.resume()
The 'resume' event is emitted when stream.resume() is\ncalled and readableFlowing is not true.
'resume'
Destroy the stream. Optionally emit an 'error' event, and emit a 'close'\nevent (unless emitClose is set to false). After this call, the readable\nstream will release any internal resources and subsequent calls to push()\nwill be ignored.
push()
Implementors should not override this method, but instead implement\nreadable._destroy().
readable._destroy()
The readable.isPaused() method returns the current operating state of the\nReadable. This is used primarily by the mechanism that underlies the\nreadable.pipe() method. In most typical cases, there will be no reason to\nuse this method directly.
readable.isPaused()
const readable = new stream.Readable();\n\nreadable.isPaused(); // === false\nreadable.pause();\nreadable.isPaused(); // === true\nreadable.resume();\nreadable.isPaused(); // === false\n
The readable.pause() method will cause a stream in flowing mode to stop\nemitting 'data' events, switching out of flowing mode. Any data that\nbecomes available will remain in the internal buffer.
const readable = getReadableStreamSomehow();\nreadable.on('data', (chunk) => {\n console.log(`Received ${chunk.length} bytes of data.`);\n readable.pause();\n console.log('There will be no additional data for 1 second.');\n setTimeout(() => {\n console.log('Now data will start flowing again.');\n readable.resume();\n }, 1000);\n});\n
The readable.pause() method has no effect if there is a 'readable'\nevent listener.
The readable.pipe() method attaches a Writable stream to the readable,\ncausing it to switch automatically into flowing mode and push all of its data\nto the attached Writable. The flow of data will be automatically managed\nso that the destination Writable stream is not overwhelmed by a faster\nReadable stream.
The following example pipes all of the data from the readable into a file\nnamed file.txt:
file.txt
const fs = require('node:fs');\nconst readable = getReadableStreamSomehow();\nconst writable = fs.createWriteStream('file.txt');\n// All the data from readable goes into 'file.txt'.\nreadable.pipe(writable);\n
It is possible to attach multiple Writable streams to a single Readable\nstream.
The readable.pipe() method returns a reference to the destination stream\nmaking it possible to set up chains of piped streams:
const fs = require('node:fs');\nconst zlib = require('node:zlib');\nconst r = fs.createReadStream('file.txt');\nconst z = zlib.createGzip();\nconst w = fs.createWriteStream('file.txt.gz');\nr.pipe(z).pipe(w);\n
By default, stream.end() is called on the destination Writable\nstream when the source Readable stream emits 'end', so that the\ndestination is no longer writable. To disable this default behavior, the end\noption can be passed as false, causing the destination stream to remain open:
end
reader.pipe(writer, { end: false });\nreader.on('end', () => {\n writer.end('Goodbye\\n');\n});\n
One important caveat is that if the Readable stream emits an error during\nprocessing, the Writable destination is not closed automatically. If an\nerror occurs, it will be necessary to manually close each stream in order\nto prevent memory leaks.
The process.stderr and process.stdout Writable streams are never\nclosed until the Node.js process exits, regardless of the specified options.
The readable.read() method reads data out of the internal buffer and\nreturns it. If no data is available to be read, null is returned. By default,\nthe data is returned as a Buffer object unless an encoding has been\nspecified using the readable.setEncoding() method or the stream is operating\nin object mode.
The optional size argument specifies a specific number of bytes to read. If\nsize bytes are not available to be read, null will be returned unless\nthe stream has ended, in which case all of the data remaining in the internal\nbuffer will be returned.
size
If the size argument is not specified, all of the data contained in the\ninternal buffer will be returned.
The size argument must be less than or equal to 1 GiB.
The readable.read() method should only be called on Readable streams\noperating in paused mode. In flowing mode, readable.read() is called\nautomatically until the internal buffer is fully drained.
const readable = getReadableStreamSomehow();\n\n// 'readable' may be triggered multiple times as data is buffered in\nreadable.on('readable', () => {\n let chunk;\n console.log('Stream is readable (new data received in buffer)');\n // Use a loop to make sure we read all currently available data\n while (null !== (chunk = readable.read())) {\n console.log(`Read ${chunk.length} bytes of data...`);\n }\n});\n\n// 'end' will be triggered once when there is no more data available\nreadable.on('end', () => {\n console.log('Reached end of stream.');\n});\n
Each call to readable.read() returns a chunk of data, or null. The chunks\nare not concatenated. A while loop is necessary to consume all data\ncurrently in the buffer. When reading a large file .read() may return null,\nhaving consumed all buffered content so far, but there is still more data to\ncome not yet buffered. In this case a new 'readable' event will be emitted\nwhen there is more data in the buffer. Finally the 'end' event will be\nemitted when there is no more data to come.
while
.read()
Therefore to read a file's whole contents from a readable, it is necessary\nto collect chunks across multiple 'readable' events:
const chunks = [];\n\nreadable.on('readable', () => {\n let chunk;\n while (null !== (chunk = readable.read())) {\n chunks.push(chunk);\n }\n});\n\nreadable.on('end', () => {\n const content = chunks.join('');\n});\n
A Readable stream in object mode will always return a single item from\na call to readable.read(size), regardless of the value of the\nsize argument.
readable.read(size)
If the readable.read() method returns a chunk of data, a 'data' event will\nalso be emitted.
Calling stream.read([size]) after the 'end' event has\nbeen emitted will return null. No runtime error will be raised.
stream.read([size])
The readable.resume() method causes an explicitly paused Readable stream to\nresume emitting 'data' events, switching the stream into flowing mode.
The readable.resume() method can be used to fully consume the data from a\nstream without actually processing any of that data:
getReadableStreamSomehow()\n .resume()\n .on('end', () => {\n console.log('Reached the end, but did not read anything.');\n });\n
The readable.resume() method has no effect if there is a 'readable'\nevent listener.
The readable.setEncoding() method sets the character encoding for\ndata read from the Readable stream.
By default, no encoding is assigned and stream data will be returned as\nBuffer objects. Setting an encoding causes the stream data\nto be returned as strings of the specified encoding rather than as Buffer\nobjects. For instance, calling readable.setEncoding('utf8') will cause the\noutput data to be interpreted as UTF-8 data, and passed as strings. Calling\nreadable.setEncoding('hex') will cause the data to be encoded in hexadecimal\nstring format.
readable.setEncoding('utf8')
readable.setEncoding('hex')
The Readable stream will properly handle multi-byte characters delivered\nthrough the stream that would otherwise become improperly decoded if simply\npulled from the stream as Buffer objects.
const readable = getReadableStreamSomehow();\nreadable.setEncoding('utf8');\nreadable.on('data', (chunk) => {\n assert.equal(typeof chunk, 'string');\n console.log('Got %d characters of string data:', chunk.length);\n});\n
The readable.unpipe() method detaches a Writable stream previously attached\nusing the stream.pipe() method.
If the destination is not specified, then all pipes are detached.
destination
If the destination is specified, but no pipe is set up for it, then\nthe method does nothing.
const fs = require('node:fs');\nconst readable = getReadableStreamSomehow();\nconst writable = fs.createWriteStream('file.txt');\n// All the data from readable goes into 'file.txt',\n// but only for the first second.\nreadable.pipe(writable);\nsetTimeout(() => {\n console.log('Stop writing to file.txt.');\n readable.unpipe(writable);\n console.log('Manually close the file stream.');\n writable.end();\n}, 1000);\n
Passing chunk as null signals the end of the stream (EOF) and behaves the\nsame as readable.push(null), after which no more data can be written. The EOF\nsignal is put at the end of the buffer and any buffered data will still be\nflushed.
readable.push(null)
The readable.unshift() method pushes a chunk of data back into the internal\nbuffer. This is useful in certain situations where a stream is being consumed by\ncode that needs to \"un-consume\" some amount of data that it has optimistically\npulled out of the source, so that the data can be passed on to some other party.
readable.unshift()
The stream.unshift(chunk) method cannot be called after the 'end' event\nhas been emitted or a runtime error will be thrown.
stream.unshift(chunk)
Developers using stream.unshift() often should consider switching to\nuse of a Transform stream instead. See the API for stream implementers\nsection for more information.
stream.unshift()
// Pull off a header delimited by \\n\\n.\n// Use unshift() if we get too much.\n// Call the callback with (error, header, stream).\nconst { StringDecoder } = require('node:string_decoder');\nfunction parseHeader(stream, callback) {\n stream.on('error', callback);\n stream.on('readable', onReadable);\n const decoder = new StringDecoder('utf8');\n let header = '';\n function onReadable() {\n let chunk;\n while (null !== (chunk = stream.read())) {\n const str = decoder.write(chunk);\n if (str.includes('\\n\\n')) {\n // Found the header boundary.\n const split = str.split(/\\n\\n/);\n header += split.shift();\n const remaining = split.join('\\n\\n');\n const buf = Buffer.from(remaining, 'utf8');\n stream.removeListener('error', callback);\n // Remove the 'readable' listener before unshifting.\n stream.removeListener('readable', onReadable);\n if (buf.length)\n stream.unshift(buf);\n // Now the body of the message can be read from the stream.\n callback(null, header, stream);\n return;\n }\n // Still reading the header.\n header += str;\n }\n }\n}\n
Unlike stream.push(chunk), stream.unshift(chunk) will not\nend the reading process by resetting the internal reading state of the stream.\nThis can cause unexpected results if readable.unshift() is called during a\nread (i.e. from within a stream._read() implementation on a\ncustom stream). Following the call to readable.unshift() with an immediate\nstream.push('') will reset the reading state appropriately,\nhowever it is best to simply avoid calling readable.unshift() while in the\nprocess of performing a read.
stream.push('')
Prior to Node.js 0.10, streams did not implement the entire node:stream\nmodule API as it is currently defined. (See Compatibility for more\ninformation.)
When using an older Node.js library that emits 'data' events and has a\nstream.pause() method that is advisory only, the\nreadable.wrap() method can be used to create a Readable stream that uses\nthe old stream as its data source.
readable.wrap()
It will rarely be necessary to use readable.wrap() but the method has been\nprovided as a convenience for interacting with older Node.js applications and\nlibraries.
const { OldReader } = require('./old-api-module.js');\nconst { Readable } = require('node:stream');\nconst oreader = new OldReader();\nconst myReader = new Readable().wrap(oreader);\n\nmyReader.on('readable', () => {\n myReader.read(); // etc.\n});\n
const fs = require('node:fs');\n\nasync function print(readable) {\n readable.setEncoding('utf8');\n let data = '';\n for await (const chunk of readable) {\n data += chunk;\n }\n console.log(data);\n}\n\nprint(fs.createReadStream('file')).catch(console.error);\n
If the loop terminates with a break, return, or a throw, the stream will\nbe destroyed. In other terms, iterating over a stream will consume the stream\nfully. The stream will be read in chunks of size equal to the highWaterMark\noption. In the code example above, data will be in a single chunk if the file\nhas less then 64 KiB of data because no highWaterMark option is provided to\nfs.createReadStream().
break
return
throw
The iterator created by this method gives users the option to cancel the\ndestruction of the stream if the for await...of loop is exited by return,\nbreak, or throw, or if the iterator should destroy the stream if the stream\nemitted an error during iteration.
for await...of
const { Readable } = require('node:stream');\n\nasync function printIterator(readable) {\n for await (const chunk of readable.iterator({ destroyOnReturn: false })) {\n console.log(chunk); // 1\n break;\n }\n\n console.log(readable.destroyed); // false\n\n for await (const chunk of readable.iterator({ destroyOnReturn: false })) {\n console.log(chunk); // Will print 2 and then 3\n }\n\n console.log(readable.destroyed); // True, stream was totally consumed\n}\n\nasync function printSymbolAsyncIterator(readable) {\n for await (const chunk of readable) {\n console.log(chunk); // 1\n break;\n }\n\n console.log(readable.destroyed); // true\n}\n\nasync function showBoth() {\n await printIterator(Readable.from([1, 2, 3]));\n await printSymbolAsyncIterator(Readable.from([1, 2, 3]));\n}\n\nshowBoth();\n
This method allows mapping over the stream. The fn function will be called\nfor every chunk in the stream. If the fn function returns a promise - that\npromise will be awaited before being passed to the result stream.
fn
await
import { Readable } from 'node:stream';\nimport { Resolver } from 'node:dns/promises';\n\n// With a synchronous mapper.\nfor await (const chunk of Readable.from([1, 2, 3, 4]).map((x) => x * 2)) {\n console.log(chunk); // 2, 4, 6, 8\n}\n// With an asynchronous mapper, making at most 2 queries at a time.\nconst resolver = new Resolver();\nconst dnsResults = Readable.from([\n 'nodejs.org',\n 'openjsf.org',\n 'www.linuxfoundation.org',\n]).map((domain) => resolver.resolve4(domain), { concurrency: 2 });\nfor await (const result of dnsResults) {\n console.log(result); // Logs the DNS result of resolver.resolve4.\n}\n
This method allows filtering the stream. For each chunk in the stream the fn\nfunction will be called and if it returns a truthy value, the chunk will be\npassed to the result stream. If the fn function returns a promise - that\npromise will be awaited.
import { Readable } from 'node:stream';\nimport { Resolver } from 'node:dns/promises';\n\n// With a synchronous predicate.\nfor await (const chunk of Readable.from([1, 2, 3, 4]).filter((x) => x > 2)) {\n console.log(chunk); // 3, 4\n}\n// With an asynchronous predicate, making at most 2 queries at a time.\nconst resolver = new Resolver();\nconst dnsResults = Readable.from([\n 'nodejs.org',\n 'openjsf.org',\n 'www.linuxfoundation.org',\n]).filter(async (domain) => {\n const { address } = await resolver.resolve4(domain, { ttl: true });\n return address.ttl > 60;\n}, { concurrency: 2 });\nfor await (const result of dnsResults) {\n // Logs domains with more than 60 seconds on the resolved dns record.\n console.log(result);\n}\n
This method allows iterating a stream. For each chunk in the stream the\nfn function will be called. If the fn function returns a promise - that\npromise will be awaited.
This method is different from for await...of loops in that it can optionally\nprocess chunks concurrently. In addition, a forEach iteration can only be\nstopped by having passed a signal option and aborting the related\nAbortController while for await...of can be stopped with break or\nreturn. In either case the stream will be destroyed.
forEach
This method is different from listening to the 'data' event in that it\nuses the readable event in the underlying machinary and can limit the\nnumber of concurrent fn calls.
import { Readable } from 'node:stream';\nimport { Resolver } from 'node:dns/promises';\n\n// With a synchronous predicate.\nfor await (const chunk of Readable.from([1, 2, 3, 4]).filter((x) => x > 2)) {\n console.log(chunk); // 3, 4\n}\n// With an asynchronous predicate, making at most 2 queries at a time.\nconst resolver = new Resolver();\nconst dnsResults = await Readable.from([\n 'nodejs.org',\n 'openjsf.org',\n 'www.linuxfoundation.org',\n]).map(async (domain) => {\n const { address } = await resolver.resolve4(domain, { ttl: true });\n return address;\n}, { concurrency: 2 });\nawait dnsResults.forEach((result) => {\n // Logs result, similar to `for await (const result of dnsResults)`\n console.log(result);\n});\nconsole.log('done'); // Stream has finished\n
This method allows easily obtaining the contents of a stream.
As this method reads the entire stream into memory, it negates the benefits of\nstreams. It's intended for interoperability and convenience, not as the primary\nway to consume streams.
import { Readable } from 'node:stream';\nimport { Resolver } from 'node:dns/promises';\n\nawait Readable.from([1, 2, 3, 4]).toArray(); // [1, 2, 3, 4]\n\n// Make dns queries concurrently using .map and collect\n// the results into an array using toArray\nconst dnsResults = await Readable.from([\n 'nodejs.org',\n 'openjsf.org',\n 'www.linuxfoundation.org',\n]).map(async (domain) => {\n const { address } = await resolver.resolve4(domain, { ttl: true });\n return address;\n}, { concurrency: 2 }).toArray();\n
This method is similar to Array.prototype.some and calls fn on each chunk\nin the stream until the awaited return value is true (or any truthy value).\nOnce an fn call on a chunk awaited return value is truthy, the stream is\ndestroyed and the promise is fulfilled with true. If none of the fn\ncalls on the chunks return a truthy value, the promise is fulfilled with\nfalse.
Array.prototype.some
import { Readable } from 'node:stream';\nimport { stat } from 'node:fs/promises';\n\n// With a synchronous predicate.\nawait Readable.from([1, 2, 3, 4]).some((x) => x > 2); // true\nawait Readable.from([1, 2, 3, 4]).some((x) => x < 0); // false\n\n// With an asynchronous predicate, making at most 2 file checks at a time.\nconst anyBigFile = await Readable.from([\n 'file1',\n 'file2',\n 'file3',\n]).some(async (fileName) => {\n const stats = await stat(fileName);\n return stat.size > 1024 * 1024;\n}, { concurrency: 2 });\nconsole.log(anyBigFile); // `true` if any file in the list is bigger than 1MB\nconsole.log('done'); // Stream has finished\n
This method is similar to Array.prototype.find and calls fn on each chunk\nin the stream to find a chunk with a truthy value for fn. Once an fn call's\nawaited return value is truthy, the stream is destroyed and the promise is\nfulfilled with value for which fn returned a truthy value. If all of the\nfn calls on the chunks return a falsy value, the promise is fulfilled with\nundefined.
Array.prototype.find
import { Readable } from 'node:stream';\nimport { stat } from 'node:fs/promises';\n\n// With a synchronous predicate.\nawait Readable.from([1, 2, 3, 4]).find((x) => x > 2); // 3\nawait Readable.from([1, 2, 3, 4]).find((x) => x > 0); // 1\nawait Readable.from([1, 2, 3, 4]).find((x) => x > 10); // undefined\n\n// With an asynchronous predicate, making at most 2 file checks at a time.\nconst foundBigFile = await Readable.from([\n 'file1',\n 'file2',\n 'file3',\n]).find(async (fileName) => {\n const stats = await stat(fileName);\n return stat.size > 1024 * 1024;\n}, { concurrency: 2 });\nconsole.log(foundBigFile); // File name of large file, if any file in the list is bigger than 1MB\nconsole.log('done'); // Stream has finished\n
This method is similar to Array.prototype.every and calls fn on each chunk\nin the stream to check if all awaited return values are truthy value for fn.\nOnce an fn call on a chunk awaited return value is falsy, the stream is\ndestroyed and the promise is fulfilled with false. If all of the fn calls\non the chunks return a truthy value, the promise is fulfilled with true.
Array.prototype.every
import { Readable } from 'node:stream';\nimport { stat } from 'node:fs/promises';\n\n// With a synchronous predicate.\nawait Readable.from([1, 2, 3, 4]).every((x) => x > 2); // false\nawait Readable.from([1, 2, 3, 4]).every((x) => x > 0); // true\n\n// With an asynchronous predicate, making at most 2 file checks at a time.\nconst allBigFiles = await Readable.from([\n 'file1',\n 'file2',\n 'file3',\n]).every(async (fileName) => {\n const stats = await stat(fileName);\n return stat.size > 1024 * 1024;\n}, { concurrency: 2 });\n// `true` if all files in the list are bigger than 1MiB\nconsole.log(allBigFiles);\nconsole.log('done'); // Stream has finished\n
This method returns a new stream by applying the given callback to each\nchunk of the stream and then flattening the result.
It is possible to return a stream or another iterable or async iterable from\nfn and the result streams will be merged (flattened) into the returned\nstream.
import { Readable } from 'node:stream';\nimport { createReadStream } from 'node:fs';\n\n// With a synchronous mapper.\nfor await (const chunk of Readable.from([1, 2, 3, 4]).flatMap((x) => [x, x])) {\n console.log(chunk); // 1, 1, 2, 2, 3, 3, 4, 4\n}\n// With an asynchronous mapper, combine the contents of 4 files\nconst concatResult = Readable.from([\n './1.mjs',\n './2.mjs',\n './3.mjs',\n './4.mjs',\n]).flatMap((fileName) => createReadStream(fileName));\nfor await (const result of concatResult) {\n // This will contain the contents (all chunks) of all 4 files\n console.log(result);\n}\n
This method returns a new stream with the first limit chunks dropped.
limit
import { Readable } from 'node:stream';\n\nawait Readable.from([1, 2, 3, 4]).drop(2).toArray(); // [3, 4]\n
This method returns a new stream with the first limit chunks.
import { Readable } from 'node:stream';\n\nawait Readable.from([1, 2, 3, 4]).take(2).toArray(); // [1, 2]\n
This method returns a new stream with chunks of the underlying stream paired\nwith a counter in the form [index, chunk]. The first index value is 0 and it\nincreases by 1 for each chunk produced.
[index, chunk]
import { Readable } from 'node:stream';\n\nconst pairs = await Readable.from(['a', 'b', 'c']).asIndexedPairs().toArray();\nconsole.log(pairs); // [[0, 'a'], [1, 'b'], [2, 'c']]\n
This method calls fn on each chunk of the stream in order, passing it the\nresult from the calculation on the previous element. It returns a promise for\nthe final value of the reduction.
The reducer function iterates the stream element-by-element which means that\nthere is no concurrency parameter or parallelism. To perform a reduce\nconcurrently, it can be chained to the readable.map method.
concurrency
reduce
readable.map
If no initial value is supplied the first chunk of the stream is used as the\ninitial value. If the stream is empty, the promise is rejected with a\nTypeError with the ERR_INVALID_ARGS code property.
initial
TypeError
ERR_INVALID_ARGS
import { Readable } from 'node:stream';\n\nconst ten = await Readable.from([1, 2, 3, 4]).reduce((previous, data) => {\n return previous + data;\n});\nconsole.log(ten); // 10\n
Is true after readable.destroy() has been called.
readable.destroy()
Is true if it is safe to call readable.read(), which means\nthe stream has not been destroyed or emitted 'error' or 'end'.
Returns whether the stream was destroyed or errored before emitting 'end'.
Returns whether 'data' has been emitted.
Getter for the property encoding of a given Readable stream. The encoding\nproperty can be set using the readable.setEncoding() method.
Becomes true when 'end' event is emitted.
This property reflects the current state of a Readable stream as described\nin the Three states section.
Returns the value of highWaterMark passed when creating this Readable.
This property contains the number of bytes (or objects) in the queue\nready to be read. The value provides introspection data regarding\nthe status of the highWaterMark.
Getter for the property objectMode of a given Readable stream.
Duplex streams are streams that implement both the Readable and\nWritable interfaces.
Examples of Duplex streams include:
If false then the stream will automatically end the writable side when the\nreadable side ends. Set initially by the allowHalfOpen constructor option,\nwhich defaults to true.
allowHalfOpen
This can be changed manually to change the half-open behavior of an existing\nDuplex stream instance, but must be changed before the 'end' event is\nemitted.
Transform streams are Duplex streams where the output is in some way\nrelated to the input. Like all Duplex streams, Transform streams\nimplement both the Readable and Writable interfaces.
Examples of Transform streams include:
Destroy the stream, and optionally emit an 'error' event. After this call, the\ntransform stream would release any internal resources.\nImplementors should not override this method, but instead implement\nreadable._destroy().\nThe default implementation of _destroy() for Transform also emit 'close'\nunless emitClose is set in false.
Once destroy() has been called, any further calls will be a no-op and no\nfurther errors except from _destroy() may be emitted as 'error'.
The node:stream module API has been designed to make it possible to easily\nimplement streams using JavaScript's prototypal inheritance model.
First, a stream developer would declare a new JavaScript class that extends one\nof the four basic stream classes (stream.Writable, stream.Readable,\nstream.Duplex, or stream.Transform), making sure they call the appropriate\nparent class constructor:
stream.Duplex
stream.Transform
const { Writable } = require('node:stream');\n\nclass MyWritable extends Writable {\n constructor({ highWaterMark, ...options }) {\n super({ highWaterMark });\n // ...\n }\n}\n
When extending streams, keep in mind what options the user\ncan and should provide before forwarding these to the base constructor. For\nexample, if the implementation makes assumptions in regard to the\nautoDestroy and emitClose options, do not allow the\nuser to override these. Be explicit about what\noptions are forwarded instead of implicitly forwarding all options.
The new stream class must then implement one or more specific methods, depending\non the type of stream being created, as detailed in the chart below:
_read()
_write()
_writev()
_final()
_transform()
_flush()
The implementation code for a stream should never call the \"public\" methods\nof a stream that are intended for use by consumers (as described in the\nAPI for stream consumers section). Doing so may lead to adverse side effects\nin application code consuming the stream.
Avoid overriding public methods such as write(), end(), cork(),\nuncork(), read() and destroy(), or emitting internal events such\nas 'error', 'data', 'end', 'finish' and 'close' through .emit().\nDoing so can break current and future stream invariants leading to behavior\nand/or compatibility issues with other streams, stream utilities, and user\nexpectations.
cork()
uncork()
read()
.emit()
For many simple cases, it is possible to create a stream without relying on\ninheritance. This can be accomplished by directly creating instances of the\nstream.Writable, stream.Readable, stream.Duplex, or stream.Transform\nobjects and passing appropriate methods as constructor options.
const { Writable } = require('node:stream');\n\nconst myWritable = new Writable({\n construct(callback) {\n // Initialize state and load resources...\n },\n write(chunk, encoding, callback) {\n // ...\n },\n destroy() {\n // Free resources...\n }\n});\n
The stream.Writable class is extended to implement a Writable stream.
Custom Writable streams must call the new stream.Writable([options])\nconstructor and implement the writable._write() and/or writable._writev()\nmethod.
new stream.Writable([options])
writable._write()
const { Writable } = require('node:stream');\n\nclass MyWritable extends Writable {\n constructor(options) {\n // Calls the stream.Writable() constructor.\n super(options);\n // ...\n }\n}\n
Or, when using pre-ES6 style constructors:
const { Writable } = require('node:stream');\nconst util = require('node:util');\n\nfunction MyWritable(options) {\n if (!(this instanceof MyWritable))\n return new MyWritable(options);\n Writable.call(this, options);\n}\nutil.inherits(MyWritable, Writable);\n
Or, using the simplified constructor approach:
const { Writable } = require('node:stream');\n\nconst myWritable = new Writable({\n write(chunk, encoding, callback) {\n // ...\n },\n writev(chunks, callback) {\n // ...\n }\n});\n
Calling abort on the AbortController corresponding to the passed\nAbortSignal will behave the same way as calling .destroy(new AbortError())\non the writeable stream.
const { Writable } = require('node:stream');\n\nconst controller = new AbortController();\nconst myWritable = new Writable({\n write(chunk, encoding, callback) {\n // ...\n },\n writev(chunks, callback) {\n // ...\n },\n signal: controller.signal\n});\n// Later, abort the operation closing the stream\ncontroller.abort();\n
The _construct() method MUST NOT be called directly. It may be implemented\nby child classes, and if so, will be called by the internal Writable\nclass methods only.
_construct()
This optional function will be called in a tick after the stream constructor\nhas returned, delaying any _write(), _final() and _destroy() calls until\ncallback is called. This is useful to initialize state or asynchronously\ninitialize resources before the stream can be used.
const { Writable } = require('node:stream');\nconst fs = require('node:fs');\n\nclass WriteStream extends Writable {\n constructor(filename) {\n super();\n this.filename = filename;\n this.fd = null;\n }\n _construct(callback) {\n fs.open(this.filename, (err, fd) => {\n if (err) {\n callback(err);\n } else {\n this.fd = fd;\n callback();\n }\n });\n }\n _write(chunk, encoding, callback) {\n fs.write(this.fd, chunk, callback);\n }\n _destroy(err, callback) {\n if (this.fd) {\n fs.close(this.fd, (er) => callback(er || err));\n } else {\n callback(err);\n }\n }\n}\n
All Writable stream implementations must provide a\nwritable._write() and/or\nwritable._writev() method to send data to the underlying\nresource.
Transform streams provide their own implementation of the\nwritable._write().
This function MUST NOT be called by application code directly. It should be\nimplemented by child classes, and called by the internal Writable class\nmethods only.
The callback function must be called synchronously inside of\nwritable._write() or asynchronously (i.e. different tick) to signal either\nthat the write completed successfully or failed with an error.\nThe first argument passed to the callback must be the Error object if the\ncall failed or null if the write succeeded.
All calls to writable.write() that occur between the time writable._write()\nis called and the callback is called will cause the written data to be\nbuffered. When the callback is invoked, the stream might emit a 'drain'\nevent. If a stream implementation is capable of processing multiple chunks of\ndata at once, the writable._writev() method should be implemented.
If the decodeStrings property is explicitly set to false in the constructor\noptions, then chunk will remain the same object that is passed to .write(),\nand may be a string rather than a Buffer. This is to support implementations\nthat have an optimized handling for certain string data encodings. In that case,\nthe encoding argument will indicate the character encoding of the string.\nOtherwise, the encoding argument can be safely ignored.
decodeStrings
.write()
The writable._write() method is prefixed with an underscore because it is\ninternal to the class that defines it, and should never be called directly by\nuser programs.
The writable._writev() method may be implemented in addition or alternatively\nto writable._write() in stream implementations that are capable of processing\nmultiple chunks of data at once. If implemented and if there is buffered data\nfrom previous writes, _writev() will be called instead of _write().
The writable._writev() method is prefixed with an underscore because it is\ninternal to the class that defines it, and should never be called directly by\nuser programs.
The _destroy() method is called by writable.destroy().\nIt can be overridden by child classes but it must not be called directly.\nFurthermore, the callback should not be mixed with async/await\nonce it is executed when a promise is resolved.
The _final() method must not be called directly. It may be implemented\nby child classes, and if so, will be called by the internal Writable\nclass methods only.
This optional function will be called before the stream closes, delaying the\n'finish' event until callback is called. This is useful to close resources\nor write buffered data before a stream ends.
Errors occurring during the processing of the writable._write(),\nwritable._writev() and writable._final() methods must be propagated\nby invoking the callback and passing the error as the first argument.\nThrowing an Error from within these methods or manually emitting an 'error'\nevent results in undefined behavior.
writable._final()
If a Readable stream pipes into a Writable stream when Writable emits an\nerror, the Readable stream will be unpiped.
const { Writable } = require('node:stream');\n\nconst myWritable = new Writable({\n write(chunk, encoding, callback) {\n if (chunk.toString().indexOf('a') >= 0) {\n callback(new Error('chunk is invalid'));\n } else {\n callback();\n }\n }\n});\n
The following illustrates a rather simplistic (and somewhat pointless) custom\nWritable stream implementation. While this specific Writable stream instance\nis not of any real particular usefulness, the example illustrates each of the\nrequired elements of a custom Writable stream instance:
const { Writable } = require('node:stream');\n\nclass MyWritable extends Writable {\n _write(chunk, encoding, callback) {\n if (chunk.toString().indexOf('a') >= 0) {\n callback(new Error('chunk is invalid'));\n } else {\n callback();\n }\n }\n}\n
Decoding buffers is a common task, for instance, when using transformers whose\ninput is a string. This is not a trivial process when using multi-byte\ncharacters encoding, such as UTF-8. The following example shows how to decode\nmulti-byte strings using StringDecoder and Writable.
StringDecoder
const { Writable } = require('node:stream');\nconst { StringDecoder } = require('node:string_decoder');\n\nclass StringWritable extends Writable {\n constructor(options) {\n super(options);\n this._decoder = new StringDecoder(options && options.defaultEncoding);\n this.data = '';\n }\n _write(chunk, encoding, callback) {\n if (encoding === 'buffer') {\n chunk = this._decoder.write(chunk);\n }\n this.data += chunk;\n callback();\n }\n _final(callback) {\n this.data += this._decoder.end();\n callback();\n }\n}\n\nconst euro = [[0xE2, 0x82], [0xAC]].map(Buffer.from);\nconst w = new StringWritable();\n\nw.write('currency: ');\nw.write(euro[0]);\nw.end(euro[1]);\n\nconsole.log(w.data); // currency: €\n
The stream.Readable class is extended to implement a Readable stream.
Custom Readable streams must call the new stream.Readable([options])\nconstructor and implement the readable._read() method.
new stream.Readable([options])
const { Readable } = require('node:stream');\n\nclass MyReadable extends Readable {\n constructor(options) {\n // Calls the stream.Readable(options) constructor.\n super(options);\n // ...\n }\n}\n
const { Readable } = require('node:stream');\nconst util = require('node:util');\n\nfunction MyReadable(options) {\n if (!(this instanceof MyReadable))\n return new MyReadable(options);\n Readable.call(this, options);\n}\nutil.inherits(MyReadable, Readable);\n
const { Readable } = require('node:stream');\n\nconst myReadable = new Readable({\n read(size) {\n // ...\n }\n});\n
Calling abort on the AbortController corresponding to the passed\nAbortSignal will behave the same way as calling .destroy(new AbortError())\non the readable created.
const { Readable } = require('node:stream');\nconst controller = new AbortController();\nconst read = new Readable({\n read(size) {\n // ...\n },\n signal: controller.signal\n});\n// Later, abort the operation closing the stream\ncontroller.abort();\n
The _construct() method MUST NOT be called directly. It may be implemented\nby child classes, and if so, will be called by the internal Readable\nclass methods only.
This optional function will be scheduled in the next tick by the stream\nconstructor, delaying any _read() and _destroy() calls until callback is\ncalled. This is useful to initialize state or asynchronously initialize\nresources before the stream can be used.
const { Readable } = require('node:stream');\nconst fs = require('node:fs');\n\nclass ReadStream extends Readable {\n constructor(filename) {\n super();\n this.filename = filename;\n this.fd = null;\n }\n _construct(callback) {\n fs.open(this.filename, (err, fd) => {\n if (err) {\n callback(err);\n } else {\n this.fd = fd;\n callback();\n }\n });\n }\n _read(n) {\n const buf = Buffer.alloc(n);\n fs.read(this.fd, buf, 0, n, null, (err, bytesRead) => {\n if (err) {\n this.destroy(err);\n } else {\n this.push(bytesRead > 0 ? buf.slice(0, bytesRead) : null);\n }\n });\n }\n _destroy(err, callback) {\n if (this.fd) {\n fs.close(this.fd, (er) => callback(er || err));\n } else {\n callback(err);\n }\n }\n}\n
This function MUST NOT be called by application code directly. It should be\nimplemented by child classes, and called by the internal Readable class\nmethods only.
All Readable stream implementations must provide an implementation of the\nreadable._read() method to fetch data from the underlying resource.
When readable._read() is called, if data is available from the resource,\nthe implementation should begin pushing that data into the read queue using the\nthis.push(dataChunk) method. _read() will be called again\nafter each call to this.push(dataChunk) once the stream is\nready to accept more data. _read() may continue reading from the resource and\npushing data until readable.push() returns false. Only when _read() is\ncalled again after it has stopped should it resume pushing additional data into\nthe queue.
this.push(dataChunk)
Once the readable._read() method has been called, it will not be called\nagain until more data is pushed through the readable.push()\nmethod. Empty data such as empty buffers and strings will not cause\nreadable._read() to be called.
The size argument is advisory. For implementations where a \"read\" is a\nsingle operation that returns data can use the size argument to determine how\nmuch data to fetch. Other implementations may ignore this argument and simply\nprovide data whenever it becomes available. There is no need to \"wait\" until\nsize bytes are available before calling stream.push(chunk).
The readable._read() method is prefixed with an underscore because it is\ninternal to the class that defines it, and should never be called directly by\nuser programs.
The _destroy() method is called by readable.destroy().\nIt can be overridden by child classes but it must not be called directly.
When chunk is a Buffer, Uint8Array, or string, the chunk of data will\nbe added to the internal queue for users of the stream to consume.\nPassing chunk as null signals the end of the stream (EOF), after which no\nmore data can be written.
When the Readable is operating in paused mode, the data added with\nreadable.push() can be read out by calling the\nreadable.read() method when the 'readable' event is\nemitted.
When the Readable is operating in flowing mode, the data added with\nreadable.push() will be delivered by emitting a 'data' event.
The readable.push() method is designed to be as flexible as possible. For\nexample, when wrapping a lower-level source that provides some form of\npause/resume mechanism, and a data callback, the low-level source can be wrapped\nby the custom Readable instance:
// `_source` is an object with readStop() and readStart() methods,\n// and an `ondata` member that gets called when it has data, and\n// an `onend` member that gets called when the data is over.\n\nclass SourceWrapper extends Readable {\n constructor(options) {\n super(options);\n\n this._source = getLowLevelSourceObject();\n\n // Every time there's data, push it into the internal buffer.\n this._source.ondata = (chunk) => {\n // If push() returns false, then stop reading from source.\n if (!this.push(chunk))\n this._source.readStop();\n };\n\n // When the source ends, push the EOF-signaling `null` chunk.\n this._source.onend = () => {\n this.push(null);\n };\n }\n // _read() will be called when the stream wants to pull more data in.\n // The advisory size argument is ignored in this case.\n _read(size) {\n this._source.readStart();\n }\n}\n
The readable.push() method is used to push the content\ninto the internal buffer. It can be driven by the readable._read() method.
For streams not operating in object mode, if the chunk parameter of\nreadable.push() is undefined, it will be treated as empty string or\nbuffer. See readable.push('') for more information.
Errors occurring during processing of the readable._read() must be\npropagated through the readable.destroy(err) method.\nThrowing an Error from within readable._read() or manually emitting an\n'error' event results in undefined behavior.
readable.destroy(err)
const { Readable } = require('node:stream');\n\nconst myReadable = new Readable({\n read(size) {\n const err = checkSomeErrorCondition();\n if (err) {\n this.destroy(err);\n } else {\n // Do some work.\n }\n }\n});\n
The following is a basic example of a Readable stream that emits the numerals\nfrom 1 to 1,000,000 in ascending order, and then ends.
const { Readable } = require('node:stream');\n\nclass Counter extends Readable {\n constructor(opt) {\n super(opt);\n this._max = 1000000;\n this._index = 1;\n }\n\n _read() {\n const i = this._index++;\n if (i > this._max)\n this.push(null);\n else {\n const str = String(i);\n const buf = Buffer.from(str, 'ascii');\n this.push(buf);\n }\n }\n}\n
A Duplex stream is one that implements both Readable and\nWritable, such as a TCP socket connection.
Because JavaScript does not have support for multiple inheritance, the\nstream.Duplex class is extended to implement a Duplex stream (as opposed\nto extending the stream.Readable and stream.Writable classes).
The stream.Duplex class prototypically inherits from stream.Readable and\nparasitically from stream.Writable, but instanceof will work properly for\nboth base classes due to overriding Symbol.hasInstance on\nstream.Writable.
instanceof
Symbol.hasInstance
Custom Duplex streams must call the new stream.Duplex([options])\nconstructor and implement both the readable._read() and\nwritable._write() methods.
new stream.Duplex([options])
const { Duplex } = require('node:stream');\n\nclass MyDuplex extends Duplex {\n constructor(options) {\n super(options);\n // ...\n }\n}\n
const { Duplex } = require('node:stream');\nconst util = require('node:util');\n\nfunction MyDuplex(options) {\n if (!(this instanceof MyDuplex))\n return new MyDuplex(options);\n Duplex.call(this, options);\n}\nutil.inherits(MyDuplex, Duplex);\n
const { Duplex } = require('node:stream');\n\nconst myDuplex = new Duplex({\n read(size) {\n // ...\n },\n write(chunk, encoding, callback) {\n // ...\n }\n});\n
When using pipeline:
const { Transform, pipeline } = require('node:stream');\nconst fs = require('node:fs');\n\npipeline(\n fs.createReadStream('object.json')\n .setEncoding('utf8'),\n new Transform({\n decodeStrings: false, // Accept string input rather than Buffers\n construct(callback) {\n this.data = '';\n callback();\n },\n transform(chunk, encoding, callback) {\n this.data += chunk;\n callback();\n },\n flush(callback) {\n try {\n // Make sure is valid json.\n JSON.parse(this.data);\n this.push(this.data);\n callback();\n } catch (err) {\n callback(err);\n }\n }\n }),\n fs.createWriteStream('valid-object.json'),\n (err) => {\n if (err) {\n console.error('failed', err);\n } else {\n console.log('completed');\n }\n }\n);\n
The following illustrates a simple example of a Duplex stream that wraps a\nhypothetical lower-level source object to which data can be written, and\nfrom which data can be read, albeit using an API that is not compatible with\nNode.js streams.\nThe following illustrates a simple example of a Duplex stream that buffers\nincoming written data via the Writable interface that is read back out\nvia the Readable interface.
const { Duplex } = require('node:stream');\nconst kSource = Symbol('source');\n\nclass MyDuplex extends Duplex {\n constructor(source, options) {\n super(options);\n this[kSource] = source;\n }\n\n _write(chunk, encoding, callback) {\n // The underlying source only deals with strings.\n if (Buffer.isBuffer(chunk))\n chunk = chunk.toString();\n this[kSource].writeSomeData(chunk);\n callback();\n }\n\n _read(size) {\n this[kSource].fetchSomeData(size, (data, encoding) => {\n this.push(Buffer.from(data, encoding));\n });\n }\n}\n
The most important aspect of a Duplex stream is that the Readable and\nWritable sides operate independently of one another despite co-existing within\na single object instance.
For Duplex streams, objectMode can be set exclusively for either the\nReadable or Writable side using the readableObjectMode and\nwritableObjectMode options respectively.
readableObjectMode
writableObjectMode
In the following example, for instance, a new Transform stream (which is a\ntype of Duplex stream) is created that has an object mode Writable side\nthat accepts JavaScript numbers that are converted to hexadecimal strings on\nthe Readable side.
const { Transform } = require('node:stream');\n\n// All Transform streams are also Duplex Streams.\nconst myTransform = new Transform({\n writableObjectMode: true,\n\n transform(chunk, encoding, callback) {\n // Coerce the chunk to a number if necessary.\n chunk |= 0;\n\n // Transform the chunk into something else.\n const data = chunk.toString(16);\n\n // Push the data onto the readable queue.\n callback(null, '0'.repeat(data.length % 2) + data);\n }\n});\n\nmyTransform.setEncoding('ascii');\nmyTransform.on('data', (chunk) => console.log(chunk));\n\nmyTransform.write(1);\n// Prints: 01\nmyTransform.write(10);\n// Prints: 0a\nmyTransform.write(100);\n// Prints: 64\n
A Transform stream is a Duplex stream where the output is computed\nin some way from the input. Examples include zlib streams or crypto\nstreams that compress, encrypt, or decrypt data.
There is no requirement that the output be the same size as the input, the same\nnumber of chunks, or arrive at the same time. For example, a Hash stream will\nonly ever have a single chunk of output which is provided when the input is\nended. A zlib stream will produce output that is either much smaller or much\nlarger than its input.
Hash
zlib
The stream.Transform class is extended to implement a Transform stream.
The stream.Transform class prototypically inherits from stream.Duplex and\nimplements its own versions of the writable._write() and\nreadable._read() methods. Custom Transform implementations must\nimplement the transform._transform() method and may\nalso implement the transform._flush() method.
transform._transform()
transform._flush()
Care must be taken when using Transform streams in that data written to the\nstream can cause the Writable side of the stream to become paused if the\noutput on the Readable side is not consumed.
const { Transform } = require('node:stream');\n\nclass MyTransform extends Transform {\n constructor(options) {\n super(options);\n // ...\n }\n}\n
const { Transform } = require('node:stream');\nconst util = require('node:util');\n\nfunction MyTransform(options) {\n if (!(this instanceof MyTransform))\n return new MyTransform(options);\n Transform.call(this, options);\n}\nutil.inherits(MyTransform, Transform);\n
const { Transform } = require('node:stream');\n\nconst myTransform = new Transform({\n transform(chunk, encoding, callback) {\n // ...\n }\n});\n
The 'end' event is from the stream.Readable class. The 'end' event is\nemitted after all data has been output, which occurs after the callback in\ntransform._flush() has been called. In the case of an error,\n'end' should not be emitted.
The 'finish' event is from the stream.Writable class. The 'finish'\nevent is emitted after stream.end() is called and all chunks\nhave been processed by stream._transform(). In the case\nof an error, 'finish' should not be emitted.
stream._transform()
In some cases, a transform operation may need to emit an additional bit of\ndata at the end of the stream. For example, a zlib compression stream will\nstore an amount of internal state used to optimally compress the output. When\nthe stream ends, however, that additional data needs to be flushed so that the\ncompressed data will be complete.
Custom Transform implementations may implement the transform._flush()\nmethod. This will be called when there is no more written data to be consumed,\nbut before the 'end' event is emitted signaling the end of the\nReadable stream.
Within the transform._flush() implementation, the transform.push() method\nmay be called zero or more times, as appropriate. The callback function must\nbe called when the flush operation is complete.
transform.push()
The transform._flush() method is prefixed with an underscore because it is\ninternal to the class that defines it, and should never be called directly by\nuser programs.
All Transform stream implementations must provide a _transform()\nmethod to accept input and produce output. The transform._transform()\nimplementation handles the bytes being written, computes an output, then passes\nthat output off to the readable portion using the transform.push() method.
The transform.push() method may be called zero or more times to generate\noutput from a single input chunk, depending on how much is to be output\nas a result of the chunk.
It is possible that no output is generated from any given chunk of input data.
The callback function must be called only when the current chunk is completely\nconsumed. The first argument passed to the callback must be an Error object\nif an error occurred while processing the input or null otherwise. If a second\nargument is passed to the callback, it will be forwarded on to the\ntransform.push() method. In other words, the following are equivalent:
transform.prototype._transform = function(data, encoding, callback) {\n this.push(data);\n callback();\n};\n\ntransform.prototype._transform = function(data, encoding, callback) {\n callback(null, data);\n};\n
The transform._transform() method is prefixed with an underscore because it\nis internal to the class that defines it, and should never be called directly by\nuser programs.
transform._transform() is never called in parallel; streams implement a\nqueue mechanism, and to receive the next chunk, callback must be\ncalled, either synchronously or asynchronously.
The stream.PassThrough class is a trivial implementation of a Transform\nstream that simply passes the input bytes across to the output. Its purpose is\nprimarily for examples and testing, but there are some use cases where\nstream.PassThrough is useful as a building block for novel sorts of streams.
stream.PassThrough
With the support of async generators and iterators in JavaScript, async\ngenerators are effectively a first-class language-level stream construct at\nthis point.
Some common interop cases of using Node.js streams with async generators\nand async iterators are provided below.
(async function() {\n for await (const chunk of readable) {\n console.log(chunk);\n }\n})();\n
Async iterators register a permanent error handler on the stream to prevent any\nunhandled post-destroy errors.
A Node.js readable stream can be created from an asynchronous generator using\nthe Readable.from() utility method:
Readable.from()
const { Readable } = require('node:stream');\n\nconst ac = new AbortController();\nconst signal = ac.signal;\n\nasync function * generate() {\n yield 'a';\n await someLongRunningFn({ signal });\n yield 'b';\n yield 'c';\n}\n\nconst readable = Readable.from(generate());\nreadable.on('close', () => {\n ac.abort();\n});\n\nreadable.on('data', (chunk) => {\n console.log(chunk);\n});\n
When writing to a writable stream from an async iterator, ensure correct\nhandling of backpressure and errors. stream.pipeline() abstracts away\nthe handling of backpressure and backpressure-related errors:
const fs = require('node:fs');\nconst { pipeline } = require('node:stream');\nconst { pipeline: pipelinePromise } = require('node:stream/promises');\n\nconst writable = fs.createWriteStream('./file');\n\nconst ac = new AbortController();\nconst signal = ac.signal;\n\nconst iterator = createIterator({ signal });\n\n// Callback Pattern\npipeline(iterator, writable, (err, value) => {\n if (err) {\n console.error(err);\n } else {\n console.log(value, 'value returned');\n }\n}).on('close', () => {\n ac.abort();\n});\n\n// Promise Pattern\npipelinePromise(iterator, writable)\n .then((value) => {\n console.log(value, 'value returned');\n })\n .catch((err) => {\n console.error(err);\n ac.abort();\n });\n
Prior to Node.js 0.10, the Readable stream interface was simpler, but also\nless powerful and less useful.
In Node.js 0.10, the Readable class was added. For backward\ncompatibility with older Node.js programs, Readable streams switch into\n\"flowing mode\" when a 'data' event handler is added, or when the\nstream.resume() method is called. The effect is that, even\nwhen not using the new stream.read() method and\n'readable' event, it is no longer necessary to worry about losing\n'data' chunks.
While most applications will continue to function normally, this introduces an\nedge case in the following conditions:
For example, consider the following code:
// WARNING! BROKEN!\nnet.createServer((socket) => {\n\n // We add an 'end' listener, but never consume the data.\n socket.on('end', () => {\n // It will never get here.\n socket.end('The message was received but was not processed.\\n');\n });\n\n}).listen(1337);\n
Prior to Node.js 0.10, the incoming message data would be simply discarded.\nHowever, in Node.js 0.10 and beyond, the socket remains paused forever.
The workaround in this situation is to call the\nstream.resume() method to begin the flow of data:
// Workaround.\nnet.createServer((socket) => {\n socket.on('end', () => {\n socket.end('The message was received but was not processed.\\n');\n });\n\n // Start the flow of data, discarding it.\n socket.resume();\n}).listen(1337);\n
In addition to new Readable streams switching into flowing mode,\npre-0.10 style streams can be wrapped in a Readable class using the\nreadable.wrap() method.
The use of readable.setEncoding() will change the behavior of how the\nhighWaterMark operates in non-object mode.
Typically, the size of the current buffer is measured against the\nhighWaterMark in bytes. However, after setEncoding() is called, the\ncomparison function will begin to measure the buffer's size in characters.
setEncoding()
This is not a problem in common cases with latin1 or ascii. But it is\nadvised to be mindful about this behavior when working with strings that could\ncontain multi-byte characters.
latin1
ascii