0
0
mirror of https://github.com/nodejs/node.git synced 2024-11-29 15:06:33 +01:00
nodejs/doc/api/stream.md

3097 lines
101 KiB
Markdown
Raw Normal View History

2012-02-27 20:18:10 +01:00
# Stream
2010-10-28 14:18:16 +02:00
<!--introduced_in=v0.10.0-->
> Stability: 2 - Stable
A stream is an abstract interface for working with streaming data in Node.js.
The `stream` module provides an API for implementing the stream interface.
2010-10-28 14:18:16 +02:00
There are many stream objects provided by Node.js. For instance, a
[request to an HTTP server][http-incoming-message] and [`process.stdout`][]
are both stream instances.
2012-02-27 20:18:10 +01:00
Streams can be readable, writable, or both. All streams are instances of
[`EventEmitter`][].
To access the `stream` module:
2012-12-13 20:15:49 +01:00
```js
const stream = require('stream');
```
2012-12-13 20:15:49 +01:00
The `stream` module is useful for creating new types of stream instances. It is
usually not necessary to use the `stream` module to consume streams.
## Organization of this document
This document contains two primary sections and a third section for notes. The
first section explains how to use existing streams within an application. The
second section explains how to create new types of streams.
## Types of streams
There are four fundamental stream types within Node.js:
* [`Writable`][]: streams to which data can be written (for example,
[`fs.createWriteStream()`][]).
* [`Readable`][]: streams from which data can be read (for example,
[`fs.createReadStream()`][]).
* [`Duplex`][]: streams that are both `Readable` and `Writable` (for example,
[`net.Socket`][]).
* [`Transform`][]: `Duplex` streams that can modify or transform the data as it
is written and read (for example, [`zlib.createDeflate()`][]).
Additionally, this module includes the utility functions
[`stream.pipeline()`][], [`stream.finished()`][] and
[`stream.Readable.from()`][].
### Object mode
All streams created by Node.js APIs operate exclusively on strings and `Buffer`
(or `Uint8Array`) objects. It is possible, however, for stream implementations
to work with other types of JavaScript values (with the exception of `null`,
which serves a special purpose within streams). Such streams are considered to
operate in "object mode".
Stream instances are switched into object mode using the `objectMode` option
when the stream is created. Attempting to switch an existing stream into
object mode is not safe.
### Buffering
2012-12-13 20:15:49 +01:00
<!--type=misc-->
2012-12-13 20:15:49 +01:00
Both [`Writable`][] and [`Readable`][] streams will store data in an internal
buffer that can be retrieved using `writable.writableBuffer` or
`readable.readableBuffer`, respectively.
The amount of data potentially buffered depends on the `highWaterMark` option
passed into the stream's constructor. For normal streams, the `highWaterMark`
option specifies a [total number of bytes][hwm-gotcha]. For streams operating
in object mode, the `highWaterMark` specifies a total number of objects.
Data is buffered in `Readable` streams when the implementation calls
[`stream.push(chunk)`][stream-push]. If the consumer of the Stream does not
call [`stream.read()`][stream-read], the data will sit in the internal
queue until it is consumed.
Once the total size of the internal read buffer reaches the threshold specified
by `highWaterMark`, the stream will temporarily stop reading data from the
underlying resource until the data currently buffered can be consumed (that is,
the stream will stop calling the internal [`readable._read()`][] method that is
used to fill the read buffer).
Data is buffered in `Writable` streams when the
[`writable.write(chunk)`][stream-write] method is called repeatedly. While the
total size of the internal write buffer is below the threshold set by
`highWaterMark`, calls to `writable.write()` will return `true`. Once
the size of the internal buffer reaches or exceeds the `highWaterMark`, `false`
will be returned.
A key goal of the `stream` API, particularly the [`stream.pipe()`][] method,
is to limit the buffering of data to acceptable levels such that sources and
destinations of differing speeds will not overwhelm the available memory.
The `highWaterMark` option is a threshold, not a limit: it dictates the amount
of data that a stream buffers before it stops asking for more data. It does not
enforce a strict memory limitation in general. Specific stream implementations
may choose to enforce stricter limits but doing so is optional.
Because [`Duplex`][] and [`Transform`][] streams are both `Readable` and
`Writable`, each maintains *two* separate internal buffers used for reading and
writing, allowing each side to operate independently of the other while
maintaining an appropriate and efficient flow of data. For example,
[`net.Socket`][] instances are [`Duplex`][] streams whose `Readable` side allows
consumption of data received *from* the socket and whose `Writable` side allows
writing data *to* the socket. Because data may be written to the socket at a
faster or slower rate than data is received, each side should
operate (and buffer) independently of the other.
## API for stream consumers
<!--type=misc-->
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:
2012-12-13 20:15:49 +01:00
```js
const http = require('http');
const server = http.createServer((req, res) => {
// `req` is an http.IncomingMessage, which is a readable stream.
// `res` is an http.ServerResponse, which is a writable stream.
let body = '';
// Get the data as utf8 strings.
// If an encoding is not set, Buffer objects will be received.
req.setEncoding('utf8');
// Readable streams emit 'data' events once a listener is added.
req.on('data', (chunk) => {
body += chunk;
});
// The 'end' event indicates that the entire body has been received.
req.on('end', () => {
try {
const data = JSON.parse(body);
// Write back something interesting to the user:
res.write(typeof data);
res.end();
} catch (er) {
// uh oh! bad json!
res.statusCode = 400;
return res.end(`error: ${er.message}`);
}
});
});
2012-12-13 20:15:49 +01:00
server.listen(1337);
// $ curl localhost:1337 -d "{}"
// object
// $ curl localhost:1337 -d "\"foo\""
// string
// $ curl localhost:1337 -d "not json"
// error: Unexpected token o in JSON at position 1
2012-12-13 20:15:49 +01:00
```
[`Writable`][] streams (such as `res` in the example) expose methods such as
`write()` and `end()` that are used to write data onto the stream.
[`Readable`][] streams use the [`EventEmitter`][] API for notifying application
code when data is available to be read off the stream. That available data can
be read from the stream in multiple ways.
Both [`Writable`][] and [`Readable`][] streams use the [`EventEmitter`][] API in
various ways to communicate the current state of the stream.
[`Duplex`][] and [`Transform`][] streams are both [`Writable`][] and
[`Readable`][].
Applications that are either writing data to or consuming data from a stream
are not required to implement the stream interfaces directly and will generally
have no reason to call `require('stream')`.
Developers wishing to implement new types of streams should refer to the
section [API for stream implementers][].
### Writable streams
Writable streams are an abstraction for a *destination* to which data is
written.
Examples of [`Writable`][] streams include:
* [HTTP requests, on the client][]
* [HTTP responses, on the server][]
* [fs write streams][]
* [zlib streams][zlib]
* [crypto streams][crypto]
* [TCP sockets][]
* [child process stdin][]
* [`process.stdout`][], [`process.stderr`][]
Some of these examples are actually [`Duplex`][] streams that implement the
[`Writable`][] interface.
All [`Writable`][] streams implement the interface defined by the
`stream.Writable` class.
While specific instances of [`Writable`][] streams may differ in various ways,
all `Writable` streams follow the same fundamental usage pattern as illustrated
in the example below:
```js
const myStream = getWritableStreamSomehow();
myStream.write('some data');
myStream.write('some more data');
myStream.end('done writing data');
```
#### Class: `stream.Writable`
<!-- YAML
added: v0.9.4
-->
2012-12-13 20:15:49 +01:00
<!--type=class-->
##### Event: `'close'`
<!-- YAML
added: v0.9.4
changes:
- version: v10.0.0
pr-url: https://github.com/nodejs/node/pull/18438
description: Add `emitClose` option to specify if `'close'` is emitted on
destroy.
-->
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.
A [`Writable`][] stream will always emit the `'close'` event if it is
created with the `emitClose` option.
##### Event: `'drain'`
<!-- YAML
added: v0.9.4
-->
If a call to [`stream.write(chunk)`][stream-write] returns `false`, the
`'drain'` event will be emitted when it is appropriate to resume writing data
to the stream.
```js
// Write the data to the supplied writable stream one million times.
// Be attentive to back-pressure.
function writeOneMillionTimes(writer, data, encoding, callback) {
let i = 1000000;
write();
function write() {
let ok = true;
do {
i--;
if (i === 0) {
// Last time!
writer.write(data, encoding, callback);
} else {
// See if we should continue, or wait.
// Don't pass the callback, because we're not done yet.
ok = writer.write(data, encoding);
}
} while (i > 0 && ok);
if (i > 0) {
// Had to stop early!
// Write some more once it drains.
writer.once('drain', write);
}
}
}
```
##### Event: `'error'`
<!-- YAML
added: v0.9.4
-->
* {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`][writable-new] option was set to `false` when creating the
stream.
After `'error'`, no further events other than `'close'` *should* be emitted
(including `'error'` events).
##### Event: `'finish'`
<!-- YAML
added: v0.9.4
-->
The `'finish'` event is emitted after the [`stream.end()`][stream-end] method
has been called, and all data has been flushed to the underlying system.
```js
const writer = getWritableStreamSomehow();
for (let i = 0; i < 100; i++) {
writer.write(`hello, #${i}!\n`);
}
writer.on('finish', () => {
console.log('All writes are now complete.');
});
writer.end('This is the end\n');
```
##### Event: `'pipe'`
<!-- YAML
added: v0.9.4
-->
* `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.
```js
const writer = getWritableStreamSomehow();
const reader = getReadableStreamSomehow();
writer.on('pipe', (src) => {
console.log('Something is piping into the writer.');
assert.equal(src, reader);
});
reader.pipe(writer);
```
##### Event: `'unpipe'`
<!-- YAML
added: v0.9.4
-->
* `src` {stream.Readable} The source stream that
[unpiped][`stream.unpipe()`] 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.
This is also emitted in case this [`Writable`][] stream emits an error when a
[`Readable`][] stream pipes into it.
```js
const writer = getWritableStreamSomehow();
const reader = getReadableStreamSomehow();
writer.on('unpipe', (src) => {
console.log('Something has stopped piping into the writer.');
assert.equal(src, reader);
});
reader.pipe(writer);
reader.unpipe(writer);
```
##### `writable.cork()`
<!-- YAML
added: v0.11.2
-->
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()`][stream-end] methods are called.
The primary intent of `writable.cork()` is to accommodate a situation in which
several small chunks are written to the stream in rapid succession. Instead of
immediately forwarding them to the underlying destination, `writable.cork()`
buffers all the chunks until `writable.uncork()` is called, which will pass them
all to `writable._writev()`, if present. This prevents a head-of-line blocking
situation where data is being buffered while waiting for the first small chunk
to be processed. However, use of `writable.cork()` without implementing
`writable._writev()` may have an adverse effect on throughput.
See also: [`writable.uncork()`][], [`writable._writev()`][stream-_writev].
##### `writable.destroy([error])`
<!-- YAML
added: v8.0.0
-->
* `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`). After this call, the writable
stream has ended and subsequent calls to `write()` or `end()` will result in
an `ERR_STREAM_DESTROYED` error.
This is a destructive and immediate way to destroy a stream. Previous calls to
`write()` may not have drained, and may trigger an `ERR_STREAM_DESTROYED` error.
Use `end()` instead of destroy if data should flush before close, or wait for
the `'drain'` event before destroying the stream.
Once `destroy()` has been called any further calls will be a noop and no
further errors except from `_destroy` may be emitted as `'error'`.
Implementors should not override this method,
but instead implement [`writable._destroy()`][writable-_destroy].
##### `writable.destroyed`
<!-- YAML
added: v8.0.0
-->
* {boolean}
Is `true` after [`writable.destroy()`][writable-destroy] has been called.
##### `writable.end([chunk[, encoding]][, callback])`
<!-- YAML
added: v0.9.4
changes:
2020-04-21, Version 14.0.0 (Current) Deprecations: - (SEMVER-MAJOR) crypto: move pbkdf2 without digest to EOL (James M Snell) [#31166](https://github.com/nodejs/node/pull/31166) - (SEMVER-MAJOR) fs: deprecate closing FileHandle on garbage collection (James M Snell) [#28396](https://github.com/nodejs/node/pull/28396) - (SEMVER-MAJOR) http: move OutboundMessage.prototype.flush to EOL (James M Snell) [#31164](https://github.com/nodejs/node/pull/31164) - (SEMVER-MAJOR) lib: move GLOBAL and root aliases to EOL (James M Snell) [#31167](https://github.com/nodejs/node/pull/31167) - (SEMVER-MAJOR) os: move tmpDir() to EOL (James M Snell)[#31169](https://github.com/nodejs/node/pull/31169) - (SEMVER-MAJOR) src: remove deprecated wasm type check (Clemens Backes) [#32116](https://github.com/nodejs/node/pull/32116) - (SEMVER-MAJOR) stream: move \_writableState.buffer to EOL (James M Snell) [#31165](https://github.com/nodejs/node/pull/31165) - (SEMVER-MINOR) doc: deprecate process.mainModule (Antoine du HAMEL) [#32232](https://github.com/nodejs/node/pull/32232) - (SEMVER-MINOR) doc: deprecate process.umask() with no arguments (Colin Ihrig) [#32499](https://github.com/nodejs/node/pull/32499) ECMAScript Modules - Experimental Warning Removal: - module: remove experimental modules warning (Guy Bedford) [#31974](https://github.com/nodejs/node/pull/31974) In Node.js 13 we removed the need to include the --experimental-modules flag, but when running EcmaScript Modules in Node.js, this would still result in a warning ExperimentalWarning: The ESM module loader is experimental. As of Node.js 14 there is no longer this warning when using ESM in Node.js. However, the ESM implementation in Node.js remains experimental. As per our stability index: “The feature is not subject to Semantic Versioning rules. Non-backward compatible changes or removal may occur in any future release.” Users should be cautious when using the feature in production environments. Please keep in mind that the implementation of ESM in Node.js differs from the developer experience you might be familiar with. Most transpilation workflows support features such as optional file extensions or JSON modules that the Node.js ESM implementation does not support. It is highly likely that modules from transpiled environments will require a certain degree of refactoring to work in Node.js. It is worth mentioning that many of our design decisions were made with two primary goals. Spec compliance and Web Compatibility. It is our belief that the current implementation offers a future proof model to authoring ESM modules that paves the path to Universal JavaScript. Please read more in our documentation. The ESM implementation in Node.js is still experimental but we do believe that we are getting very close to being able to call ESM in Node.js “stable”. Removing the warning is a huge step in that direction. New V8 ArrayBuffer API: * **src**: migrate to new V8 ArrayBuffer API (Thang Tran) [#30782](https://github.com/nodejs/node/pull/30782) Multiple ArrayBuffers pointing to the same base address are no longer allowed by V8. This may impact native addons. Toolchain and Compiler Upgrades: - (SEMVER-MAJOR) build: update macos deployment target to 10.13 for 14.x (AshCripps)[#32454](https://github.com/nodejs/node/pull/32454) - (SEMVER-MAJOR) doc: update cross compiler machine for Linux armv7 (Richard Lau) [#32812](https://github.com/nodejs/node/pull/32812) - (SEMVER-MAJOR) doc: update Centos/RHEL releases use devtoolset-8 (Richard Lau) [#32812](https://github.com/nodejs/node/pull/32812) - (SEMVER-MAJOR) doc: remove SmartOS from official binaries (Richard Lau) [#32812](https://github.com/nodejs/node/pull/32812) - (SEMVER-MAJOR) win: block running on EOL Windows versions (João Reis) [#31954](https://github.com/nodejs/node/pull/31954) It is expected that there will be an ABI mismatch on ARM between the Node.js binary and native addons. Native addons are only broken if they interact with `std::shared_ptr`. This is expected to be fixed in a later version of Node.js 14. - [#30786](https://github.com/nodejs/node/issues/30786) Update to V8 8.1: - (SEMVER-MAJOR) deps: update V8 to 8.1.307.20 (Matheus Marchini) [#32116](https://github.com/nodejs/node/pull/32116) Other Notable Changes: - cli, report: move --report-on-fatalerror to stable (Colin Ihrig) [#32496](https://github.com/nodejs/node/pull/32496) - deps: upgrade to libuv 1.37.0 (Colin Ihrig) [#32866](https://github.com/nodejs/node/pull/32866) - fs: add fs/promises alias module (Gus Caplan) [#31553](https://github.com/nodejs/node/pull/31553) PR-URL: https://github.com/nodejs/node/pull/32181
2020-03-10 18:16:08 +01:00
- version: v14.0.0
pr-url: https://github.com/nodejs/node/pull/29747
description: The `callback` is invoked if 'finish' or 'error' is emitted.
2018-04-24, Version 10.0.0 (Current) * Assert * Calling `assert.fail()` with more than one argument is deprecated. #70dcacd710 * Calling `assert.ok()` with no arguments will now throw. #3cd7977a42 * Calling `assert.ifError()` will now throw with any argument other than `undefined` or `null`. Previously the method would throw with any truthy value. #e65a6e81ef * The `assert.rejects()` and `assert.doesNotReject()` methods have been added for working with async functions. #599337f43e * Async_hooks * Older experimental async_hooks APIs have been removed. #1cc6b993b9 * Buffer * Uses of `new Buffer()` and `Buffer()` outside of the `node_modules` directory will now emit a runtime deprecation warning. #9d4ab90117 * `Buffer.isEncoding()` now returns `undefined` for falsy values, including an empty string. #452eed956e * `Buffer.fill()` will throw if an attempt is made to fill with an empty `Buffer`. #1e802539b2 * Child Process * Undefined properties of env are ignored. #38ee25e2e2, #85739b6c5b * Console * The `console.table()` method has been added. #97ace04492 * Crypto * The `crypto.createCipher()` and `crypto.createDecipher()` methods have been deprecated. Please use `crypto.createCipheriv()` and `crypto.createDecipheriv()` instead. #81f88e30dd * The `decipher.finaltol()` method has been deprecated. #19f3927d92 * The `crypto.DEFAULT_ENCODING` property has been deprecated. #6035beea93 * The `ECDH.convertKey()` method has been added. #f2e02883e7 * The `crypto.fips` property has been deprecated. #6e7992e8b8 * Dependencies * V8 has been updated to 6.6. #9daebb48d6 * OpenSSL has been updated to 1.1.0h. #66cb29e646 * EventEmitter * The `EventEmitter.prototype.off()` method has been added as an alias for `EventEmitter.prototype.removeListener()`. #3bb6f07d52 * File System * The `fs.promises` API provides experimental promisified versions of the `fs` functions. #329fc78e49 * Invalid path errors are now thrown synchronously. #d8f73385e2 * The `fs.readFile()` method now partitions reads to avoid thread pool exhaustion. #67a4ce1c6e * HTTP * Processing of HTTP Status codes `100`, `102-199` has been improved. #baf8495078 * Multi-byte characters in URL paths are now forbidden. #b961d9fd83 * N-API * The n-api is no longer experimental. #cd7d7b15c1 * Net * The `'close'` event will be emitted after `'end'`. #9b7a6914a7 * Perf_hooks * The `PerformanceObserver` class is now an `AsyncResource` and can be monitored using `async_hooks`. #009e41826f * Trace events are now emitted for performance events. #9e509b622b * The `performance` API has been simplified. #2ec6995555 * Performance milestone marks will be emitted as trace events. #96cb4fb795 * Process * Using non-string values for `process.env` is deprecated. #5826fe4e79 * The `process.assert()` method is deprecated. #703e37cf3f * REPL * REPL now experimentally supports top-level await when using the `--experimental-repl-await` flag. #eeab7bc068 * The previously deprecated "magic mode" has been removed. #4893f70d12 * The previously deprecated `NODE_REPL_HISTORY_FILE` environment variable has been removed. #60c9ad7979 * Proxy objects are shown as Proxy objects when inspected. #90a43906ab * Streams * The `'readable'` event is now always deferred with nextTick. #1e0f3315c7 * A new `pipeline()` method has been provided for building end-to-data stream pipelines. #a5cf3feaf1 * Experimental support for async for-await has been added to `stream.Readable`. #61b4d60c5d * Timers * The `enroll()` and `unenroll()` methods have been deprecated. #68783ae0b8 * TLS * The `tls.convertNONProtocols()` method has been deprecated. #9204a0db6e * Support for NPN (next protocol negotiation) has been dropped. #5bfbe5ceae * The `ecdhCurve` default is now `'auto'`. #af78840b19 * Trace Events * A new `trace_events` top-level module allows trace event categories to be enabled/disabld at runtime. #da5d818a54 * URL * The WHATWG URL API is now a global. #312414662b * Util * `util.types.is[…]` type checks have been added. #b20af8088a * Support for bigint formatting has been added to `util.inspect()`. #39dc947409
2018-03-02 18:53:46 +01:00
- version: v10.0.0
pr-url: https://github.com/nodejs/node/pull/18780
description: This method now returns a reference to `writable`.
2017-05-30, Version 8.0.0 (Current) * **Async Hooks** * The `async_hooks` module has landed in core [[`4a7233c178`](https://github.com/nodejs/node/commit/4a7233c178)] [#12892](https://github.com/nodejs/node/pull/12892). * **Buffer** * Using the `--pending-deprecation` flag will cause Node.js to emit a deprecation warning when using `new Buffer(num)` or `Buffer(num)`. [[`d2d32ea5a2`](https://github.com/nodejs/node/commit/d2d32ea5a2)] [#11968](https://github.com/nodejs/node/pull/11968). * `new Buffer(num)` and `Buffer(num)` will zero-fill new `Buffer` instances [[`7eb1b4658e`](https://github.com/nodejs/node/commit/7eb1b4658e)] [#12141](https://github.com/nodejs/node/pull/12141). * Many `Buffer` methods now accept `Uint8Array` as input [[`beca3244e2`](https://github.com/nodejs/node/commit/beca3244e2)] [#10236](https://github.com/nodejs/node/pull/10236). * **Child Process** * Argument and kill signal validations have been improved [[`97a77288ce`](https://github.com/nodejs/node/commit/97a77288ce)] [#12348](https://github.com/nodejs/node/pull/12348), [[`d75fdd96aa`](https://github.com/nodejs/node/commit/d75fdd96aa)] [#10423](https://github.com/nodejs/node/pull/10423). * Child Process methods accept `Uint8Array` as input [[`627ecee9ed`](https://github.com/nodejs/node/commit/627ecee9ed)] [#10653](https://github.com/nodejs/node/pull/10653). * **Console** * Error events emitted when using `console` methods are now supressed. [[`f18e08d820`](https://github.com/nodejs/node/commit/f18e08d820)] [#9744](https://github.com/nodejs/node/pull/9744). * **Dependencies** * The npm client has been updated to 5.0.0 [[`3c3b36af0f`](https://github.com/nodejs/node/commit/3c3b36af0f)] [#12936](https://github.com/nodejs/node/pull/12936). * V8 has been updated to 5.8 with forward ABI stability to 6.0 [[`60d1aac8d2`](https://github.com/nodejs/node/commit/60d1aac8d2)] [#12784](https://github.com/nodejs/node/pull/12784). * **Domains** * Native `Promise` instances are now `Domain` aware [[`84dabe8373`](https://github.com/nodejs/node/commit/84dabe8373)] [#12489](https://github.com/nodejs/node/pull/12489). * **Errors** * We have started assigning static error codes to errors generated by Node.js. This has been done through multiple commits and is still a work in progress. * **File System** * The utility class `fs.SyncWriteStream` has been deprecated [[`7a55e34ef4`](https://github.com/nodejs/node/commit/7a55e34ef4)] [#10467](https://github.com/nodejs/node/pull/10467). * The deprecated `fs.read()` string interface has been removed [[`3c2a9361ff`](https://github.com/nodejs/node/commit/3c2a9361ff)] [#9683](https://github.com/nodejs/node/pull/9683). * **HTTP** * Improved support for userland implemented Agents [[`90403dd1d0`](https://github.com/nodejs/node/commit/90403dd1d0)] [#11567](https://github.com/nodejs/node/pull/11567). * Outgoing Cookie headers are concatenated into a single string [[`d3480776c7`](https://github.com/nodejs/node/commit/d3480776c7)] [#11259](https://github.com/nodejs/node/pull/11259). * The `httpResponse.writeHeader()` method has been deprecated [[`fb71ba4921`](https://github.com/nodejs/node/commit/fb71ba4921)] [#11355](https://github.com/nodejs/node/pull/11355). * New methods for accessing HTTP headers have been added to `OutgoingMessage` [[`3e6f1032a4`](https://github.com/nodejs/node/commit/3e6f1032a4)] [#10805](https://github.com/nodejs/node/pull/10805). * **Lib** * All deprecation messages have been assigned static identifiers [[`5de3cf099c`](https://github.com/nodejs/node/commit/5de3cf099c)] [#10116](https://github.com/nodejs/node/pull/10116). * The legacy `linkedlist` module has been removed [[`84a23391f6`](https://github.com/nodejs/node/commit/84a23391f6)] [#12113](https://github.com/nodejs/node/pull/12113). * **N-API** * Experimental support for the new N-API API has been added [[`56e881d0b0`](https://github.com/nodejs/node/commit/56e881d0b0)] [#11975](https://github.com/nodejs/node/pull/11975). * **Process** * Process warning output can be redirected to a file using the `--redirect-warnings` command-line argument [[`03e89b3ff2`](https://github.com/nodejs/node/commit/03e89b3ff2)] [#10116](https://github.com/nodejs/node/pull/10116). * Process warnings may now include additional detail [[`dd20e68b0f`](https://github.com/nodejs/node/commit/dd20e68b0f)] [#12725](https://github.com/nodejs/node/pull/12725). * **REPL** * REPL magic mode has been deprecated [[`3f27f02da0`](https://github.com/nodejs/node/commit/3f27f02da0)] [#11599](https://github.com/nodejs/node/pull/11599). * **Src** * `NODE_MODULE_VERSION` has been updated to 57 (https://github.com/nodejs/node/commit/ec7cbaf266)] [#12995](https://github.com/nodejs/node/pull/12995). * Add `--pending-deprecation` command-line argument and `NODE_PENDING_DEPRECATION` environment variable [[`a16b570f8c`](https://github.com/nodejs/node/commit/a16b570f8c)] [#11968](https://github.com/nodejs/node/pull/11968). * The `--debug` command-line argument has been deprecated. Note that using `--debug` will enable the *new* Inspector-based debug protocol as the legacy Debugger protocol previously used by Node.js has been removed. [[`010f864426`](https://github.com/nodejs/node/commit/010f864426)] [#12949](https://github.com/nodejs/node/pull/12949). * Throw when the `-c` and `-e` command-line arguments are used at the same time [[`a5f91ab230`](https://github.com/nodejs/node/commit/a5f91ab230)] [#11689](https://github.com/nodejs/node/pull/11689). * Throw when the `--use-bundled-ca` and `--use-openssl-ca` command-line arguments are used at the same time. [[`8a7db9d4b5`](https://github.com/nodejs/node/commit/8a7db9d4b5)] [#12087](https://github.com/nodejs/node/pull/12087). * **Stream** * `Stream` now supports `destroy()` and `_destroy()` APIs [[`b6e1d22fa6`](https://github.com/nodejs/node/commit/b6e1d22fa6)] [#12925](https://github.com/nodejs/node/pull/12925). * `Stream` now supports the `_final()` API [[`07c7f198db`](https://github.com/nodejs/node/commit/07c7f198db)] [#12828](https://github.com/nodejs/node/pull/12828). * **TLS** * The `rejectUnauthorized` option now defaults to `true` [[`348cc80a3c`](https://github.com/nodejs/node/commit/348cc80a3c)] [#5923](https://github.com/nodejs/node/pull/5923). * The `tls.createSecurePair()` API now emits a runtime deprecation [[`a2ae08999b`](https://github.com/nodejs/node/commit/a2ae08999b)] [#11349](https://github.com/nodejs/node/pull/11349). * A runtime deprecation will now be emitted when `dhparam` is less than 2048 bits [[`d523eb9c40`](https://github.com/nodejs/node/commit/d523eb9c40)] [#11447](https://github.com/nodejs/node/pull/11447). * **URL** * The WHATWG URL implementation is now a fully-supported Node.js API [[`d080ead0f9`](https://github.com/nodejs/node/commit/d080ead0f9)] [#12710](https://github.com/nodejs/node/pull/12710). * **Util** * `Symbol` keys are now displayed by default when using `util.inspect()` [[`5bfd13b81e`](https://github.com/nodejs/node/commit/5bfd13b81e)] [#9726](https://github.com/nodejs/node/pull/9726). * `toJSON` errors will be thrown when formatting `%j` [[`455e6f1dd8`](https://github.com/nodejs/node/commit/455e6f1dd8)] [#11708](https://github.com/nodejs/node/pull/11708). * Convert `inspect.styles` and `inspect.colors` to prototype-less objects [[`aab0d202f8`](https://github.com/nodejs/node/commit/aab0d202f8)] [#11624](https://github.com/nodejs/node/pull/11624). * The new `util.promisify()` API has been added [[`99da8e8e02`](https://github.com/nodejs/node/commit/99da8e8e02)] [#12442](https://github.com/nodejs/node/pull/12442). * **Zlib** * Support `Uint8Array` in Zlib convenience methods [[`91383e47fd`](https://github.com/nodejs/node/commit/91383e47fd)] [#12001](https://github.com/nodejs/node/pull/12001). * Zlib errors now use `RangeError` and `TypeError` consistently [[`b514bd231e`](https://github.com/nodejs/node/commit/b514bd231e)] [#11391](https://github.com/nodejs/node/pull/11391).
2017-03-16 04:26:14 +01:00
- version: v8.0.0
pr-url: https://github.com/nodejs/node/pull/11608
description: The `chunk` argument can now be a `Uint8Array` instance.
-->
* `chunk` {string|Buffer|Uint8Array|any} Optional data to write. For streams
not operating in object mode, `chunk` must be a string, `Buffer` or
`Uint8Array`. For object mode streams, `chunk` may be any JavaScript value
other than `null`.
* `encoding` {string} The encoding if `chunk` is a string
* `callback` {Function} Optional callback for when the stream finishes
or errors
* Returns: {this}
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. If provided, the optional `callback` function is attached as a listener
for the [`'finish'`][] and the `'error'` event.
Calling the [`stream.write()`][stream-write] method after calling
[`stream.end()`][stream-end] will raise an error.
```js
// Write 'hello, ' and then end with 'world!'.
const fs = require('fs');
const file = fs.createWriteStream('example.txt');
file.write('hello, ');
file.end('world!');
// Writing more now is not allowed!
```
##### `writable.setDefaultEncoding(encoding)`
<!-- YAML
added: v0.11.15
changes:
- version: v6.1.0
pr-url: https://github.com/nodejs/node/pull/5040
description: This method now returns a reference to `writable`.
-->
* `encoding` {string} The new default encoding
* Returns: {this}
The `writable.setDefaultEncoding()` method sets the default `encoding` for a
[`Writable`][] stream.
##### `writable.uncork()`
<!-- YAML
added: v0.11.2
-->
The `writable.uncork()` method flushes all data buffered since
[`stream.cork()`][] was called.
When using [`writable.cork()`][] and `writable.uncork()` to manage the buffering
of writes to a stream, it is recommended that calls to `writable.uncork()` be
deferred using `process.nextTick()`. Doing so allows batching of all
`writable.write()` calls that occur within a given Node.js event loop phase.
```js
stream.cork();
stream.write('some ');
stream.write('data ');
process.nextTick(() => stream.uncork());
```
If the [`writable.cork()`][] method is called multiple times on a stream, the
same number of calls to `writable.uncork()` must be called to flush the buffered
data.
```js
stream.cork();
stream.write('some ');
stream.cork();
stream.write('data ');
process.nextTick(() => {
stream.uncork();
// The data will not be flushed until uncork() is called a second time.
stream.uncork();
});
```
See also: [`writable.cork()`][].
##### `writable.writable`
<!-- YAML
added: v11.4.0
-->
* {boolean}
Is `true` if it is safe to call [`writable.write()`][stream-write], which means
the stream has not been destroyed, errored or ended.
##### `writable.writableEnded`
<!-- YAML
2019-08-20, Version 12.9.0 (Current) Notable changes: * crypto: * Added an oaepHash option to asymmetric encryption which allows users to specify a hash function when using OAEP padding. https://github.com/nodejs/node/pull/28335 * deps: * Updated V8 to 7.6.303.29. https://github.com/nodejs/node/pull/28955 * Improves the performance of various APIs such as `JSON.parse` and methods called on frozen arrays. * Adds the Promise.allSettled method. * Improves support of `BigInt` in `Intl` methods. * For more information: https://v8.dev/blog/v8-release-76 * Updated libuv to 1.31.0. https://github.com/nodejs/node/pull/29070 * `UV_FS_O_FILEMAP` has been added for faster access to memory mapped files on Windows. * `uv_fs_mkdir()` now returns `UV_EINVAL` for invalid filenames on Windows. It previously returned `UV_ENOENT`. * The `uv_fs_statfs()` API has been added. * The `uv_os_environ()` and `uv_os_free_environ()` APIs have been added. * fs: * Added `fs.writev`, `fs.writevSync` and `filehandle.writev` (promise version) methods. They allow to write an array of `ArrayBufferView`s to a file descriptor. https://github.com/nodejs/node/pull/25925 https://github.com/nodejs/node/pull/29186 * http: * Added three properties to `OutgoingMessage.prototype`: `writableObjectMode`, `writableLength` and `writableHighWaterMark` https://github.com/nodejs/node/pull/29018 * stream: * Added an new property `readableEnded` to readable streams. Its value is set to `true` when the `'end'` event is emitted. https://github.com/nodejs/node/pull/28814 * Added an new property `writableEnded` to writable streams. Its value is set to `true` after `writable.end()` has been called. https://github.com/nodejs/node/pull/28934 PR-URL: https://github.com/nodejs/node/pull/29210
2019-08-19 21:14:22 +02:00
added: v12.9.0
-->
* {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.
##### `writable.writableCorked`
<!-- YAML
added:
- v13.2.0
- v12.16.0
-->
* {integer}
Number of times [`writable.uncork()`][stream-uncork] needs to be
called in order to fully uncork the stream.
##### `writable.writableFinished`
<!-- YAML
added: v12.6.0
-->
* {boolean}
Is set to `true` immediately before the [`'finish'`][] event is emitted.
##### `writable.writableHighWaterMark`
<!-- YAML
2017-12-12 Version 9.3.0 (Current) Notable changes: * async\_hooks: - add trace events to async_hooks (Andreas Madsen) https://github.com/nodejs/node/pull/15538 - add provider types for net server (Andreas Madsen) https://github.com/nodejs/node/pull/17157 * console: - console.debug can now be used outside of the inspector (Benjamin Zaslavsky) https://github.com/nodejs/node/pull/17033 * deps: - upgrade libuv to 1.18.0 (cjihrig) https://github.com/nodejs/node/pull/17282 - patch V8 to 6.2.414.46 (Myles Borins) https://github.com/nodejs/node/pull/17206 * module: - module.builtinModules will return a list of built in modules (Jon Moss) https://github.com/nodejs/node/pull/16386 * n-api: - add helper for addons to get the event loop (Anna Henningsen) https://github.com/nodejs/node/pull/17109 * process: - process.setUncaughtExceptionCaptureCallback can now be used to customize behavior for `--abort-on-uncaught-exception` (Anna Henningsen) https://github.com/nodejs/node/pull/17159 - A signal handler is now able to receive the signal code that triggered the handler. (Robert Rossmann) https://github.com/nodejs/node/pull/15606 * src: - embedders can now use Node::CreatePlatform to create an instance of NodePlatform (Cheng Zhao) https://github.com/nodejs/node/pull/16981 * stream: - writable.writableHighWaterMark and readable.readableHighWaterMark will return the values the stream object was instantiated with (Calvin Metcalf) https://github.com/nodejs/node/pull/12860 * **Added new collaborators** * [maclover7](https://github.com/maclover7) Jon Moss * [guybedford](https://github.com/guybedford) Guy Bedford * [hashseed](https://github.com/hashseed) Yang Guo PR-URL: https://github.com/nodejs/node/pull/17631
2017-12-12 09:09:37 +01:00
added: v9.3.0
-->
* {number}
Return the value of `highWaterMark` passed when creating this `Writable`.
##### `writable.writableLength`
<!-- YAML
2019-01-10 Version 9.4.0 (Current) Notable change: * async_hooks: - deprecate AsyncHooks Sensitive API and runInAsyncIdScope. Neither API were documented. (Andreas Madsen) https://github.com/nodejs/node/pull/16972 * deps: - update nghttp2 to 1.29.0 (James M Snell) https://github.com/nodejs/node/pull/17908 - upgrade npm to 5.6.0 (Kat Marchán) https://github.com/nodejs/node/pull/17535 - cherry-pick 50f7455 from upstream V8 (Michaël Zasso) https://github.com/nodejs/node/pull/16591 * events: - remove reaches into _events internals (Anatoli Papirovski) https://github.com/nodejs/node/pull/17440 * http: - add rawPacket in err of `clientError` event (XadillaX) https://github.com/nodejs/node/pull/17672 * http2: - implement maxSessionMemory (James M Snell) https://github.com/nodejs/node/pull/17967 - add initial support for originSet (James M Snell) https://github.com/nodejs/node/pull/17935 - add altsvc support (James M Snell) https://github.com/nodejs/node/pull/17917 - perf_hooks integration (James M Snell) https://github.com/nodejs/node/pull/17906 - Refactoring and cleanup of Http2Session and Http2Stream destroy (James M Snell) https://github.com/nodejs/node/pull/17406 * net: - remove Socket.prototype.write (Anna Henningsen) https://github.com/nodejs/node/pull/17644 - remove Socket.prototype.listen (Ruben Bridgewater) https://github.com/nodejs/node/pull/13735 * repl: - show lexically scoped vars in tab completion (Michaël Zasso) https://github.com/nodejs/node/pull/16591 * stream: - rm {writeable/readable}State.length (Calvin Metcalf) https://github.com/nodejs/node/pull/12857 - add flow and buffer properties to streams (Calvin Metcalf) https://github.com/nodejs/node/pull/12855 * util: - allow wildcards in NODE_DEBUG variable (Tyler) https://github.com/nodejs/node/pull/17609 * zlib: - add ArrayBuffer support (Jem Bezooyen) https://github.com/nodejs/node/pull/16042 * Addedew collaborator** - [starkwang](https://github.com/starkwang) Weijia Wang * Addedew TSC member** - [danbev](https://github.com/danbev) Daniel Bevenius PR-URL: https://github.com/nodejs/node/pull/18069
2018-01-10 01:23:55 +01:00
added: v9.4.0
-->
* {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`.
##### `writable.writableObjectMode`
<!-- YAML
added: v12.3.0
-->
* {boolean}
Getter for the property `objectMode` of a given `Writable` stream.
##### `writable.write(chunk[, encoding][, callback])`
<!-- YAML
added: v0.9.4
changes:
2017-05-30, Version 8.0.0 (Current) * **Async Hooks** * The `async_hooks` module has landed in core [[`4a7233c178`](https://github.com/nodejs/node/commit/4a7233c178)] [#12892](https://github.com/nodejs/node/pull/12892). * **Buffer** * Using the `--pending-deprecation` flag will cause Node.js to emit a deprecation warning when using `new Buffer(num)` or `Buffer(num)`. [[`d2d32ea5a2`](https://github.com/nodejs/node/commit/d2d32ea5a2)] [#11968](https://github.com/nodejs/node/pull/11968). * `new Buffer(num)` and `Buffer(num)` will zero-fill new `Buffer` instances [[`7eb1b4658e`](https://github.com/nodejs/node/commit/7eb1b4658e)] [#12141](https://github.com/nodejs/node/pull/12141). * Many `Buffer` methods now accept `Uint8Array` as input [[`beca3244e2`](https://github.com/nodejs/node/commit/beca3244e2)] [#10236](https://github.com/nodejs/node/pull/10236). * **Child Process** * Argument and kill signal validations have been improved [[`97a77288ce`](https://github.com/nodejs/node/commit/97a77288ce)] [#12348](https://github.com/nodejs/node/pull/12348), [[`d75fdd96aa`](https://github.com/nodejs/node/commit/d75fdd96aa)] [#10423](https://github.com/nodejs/node/pull/10423). * Child Process methods accept `Uint8Array` as input [[`627ecee9ed`](https://github.com/nodejs/node/commit/627ecee9ed)] [#10653](https://github.com/nodejs/node/pull/10653). * **Console** * Error events emitted when using `console` methods are now supressed. [[`f18e08d820`](https://github.com/nodejs/node/commit/f18e08d820)] [#9744](https://github.com/nodejs/node/pull/9744). * **Dependencies** * The npm client has been updated to 5.0.0 [[`3c3b36af0f`](https://github.com/nodejs/node/commit/3c3b36af0f)] [#12936](https://github.com/nodejs/node/pull/12936). * V8 has been updated to 5.8 with forward ABI stability to 6.0 [[`60d1aac8d2`](https://github.com/nodejs/node/commit/60d1aac8d2)] [#12784](https://github.com/nodejs/node/pull/12784). * **Domains** * Native `Promise` instances are now `Domain` aware [[`84dabe8373`](https://github.com/nodejs/node/commit/84dabe8373)] [#12489](https://github.com/nodejs/node/pull/12489). * **Errors** * We have started assigning static error codes to errors generated by Node.js. This has been done through multiple commits and is still a work in progress. * **File System** * The utility class `fs.SyncWriteStream` has been deprecated [[`7a55e34ef4`](https://github.com/nodejs/node/commit/7a55e34ef4)] [#10467](https://github.com/nodejs/node/pull/10467). * The deprecated `fs.read()` string interface has been removed [[`3c2a9361ff`](https://github.com/nodejs/node/commit/3c2a9361ff)] [#9683](https://github.com/nodejs/node/pull/9683). * **HTTP** * Improved support for userland implemented Agents [[`90403dd1d0`](https://github.com/nodejs/node/commit/90403dd1d0)] [#11567](https://github.com/nodejs/node/pull/11567). * Outgoing Cookie headers are concatenated into a single string [[`d3480776c7`](https://github.com/nodejs/node/commit/d3480776c7)] [#11259](https://github.com/nodejs/node/pull/11259). * The `httpResponse.writeHeader()` method has been deprecated [[`fb71ba4921`](https://github.com/nodejs/node/commit/fb71ba4921)] [#11355](https://github.com/nodejs/node/pull/11355). * New methods for accessing HTTP headers have been added to `OutgoingMessage` [[`3e6f1032a4`](https://github.com/nodejs/node/commit/3e6f1032a4)] [#10805](https://github.com/nodejs/node/pull/10805). * **Lib** * All deprecation messages have been assigned static identifiers [[`5de3cf099c`](https://github.com/nodejs/node/commit/5de3cf099c)] [#10116](https://github.com/nodejs/node/pull/10116). * The legacy `linkedlist` module has been removed [[`84a23391f6`](https://github.com/nodejs/node/commit/84a23391f6)] [#12113](https://github.com/nodejs/node/pull/12113). * **N-API** * Experimental support for the new N-API API has been added [[`56e881d0b0`](https://github.com/nodejs/node/commit/56e881d0b0)] [#11975](https://github.com/nodejs/node/pull/11975). * **Process** * Process warning output can be redirected to a file using the `--redirect-warnings` command-line argument [[`03e89b3ff2`](https://github.com/nodejs/node/commit/03e89b3ff2)] [#10116](https://github.com/nodejs/node/pull/10116). * Process warnings may now include additional detail [[`dd20e68b0f`](https://github.com/nodejs/node/commit/dd20e68b0f)] [#12725](https://github.com/nodejs/node/pull/12725). * **REPL** * REPL magic mode has been deprecated [[`3f27f02da0`](https://github.com/nodejs/node/commit/3f27f02da0)] [#11599](https://github.com/nodejs/node/pull/11599). * **Src** * `NODE_MODULE_VERSION` has been updated to 57 (https://github.com/nodejs/node/commit/ec7cbaf266)] [#12995](https://github.com/nodejs/node/pull/12995). * Add `--pending-deprecation` command-line argument and `NODE_PENDING_DEPRECATION` environment variable [[`a16b570f8c`](https://github.com/nodejs/node/commit/a16b570f8c)] [#11968](https://github.com/nodejs/node/pull/11968). * The `--debug` command-line argument has been deprecated. Note that using `--debug` will enable the *new* Inspector-based debug protocol as the legacy Debugger protocol previously used by Node.js has been removed. [[`010f864426`](https://github.com/nodejs/node/commit/010f864426)] [#12949](https://github.com/nodejs/node/pull/12949). * Throw when the `-c` and `-e` command-line arguments are used at the same time [[`a5f91ab230`](https://github.com/nodejs/node/commit/a5f91ab230)] [#11689](https://github.com/nodejs/node/pull/11689). * Throw when the `--use-bundled-ca` and `--use-openssl-ca` command-line arguments are used at the same time. [[`8a7db9d4b5`](https://github.com/nodejs/node/commit/8a7db9d4b5)] [#12087](https://github.com/nodejs/node/pull/12087). * **Stream** * `Stream` now supports `destroy()` and `_destroy()` APIs [[`b6e1d22fa6`](https://github.com/nodejs/node/commit/b6e1d22fa6)] [#12925](https://github.com/nodejs/node/pull/12925). * `Stream` now supports the `_final()` API [[`07c7f198db`](https://github.com/nodejs/node/commit/07c7f198db)] [#12828](https://github.com/nodejs/node/pull/12828). * **TLS** * The `rejectUnauthorized` option now defaults to `true` [[`348cc80a3c`](https://github.com/nodejs/node/commit/348cc80a3c)] [#5923](https://github.com/nodejs/node/pull/5923). * The `tls.createSecurePair()` API now emits a runtime deprecation [[`a2ae08999b`](https://github.com/nodejs/node/commit/a2ae08999b)] [#11349](https://github.com/nodejs/node/pull/11349). * A runtime deprecation will now be emitted when `dhparam` is less than 2048 bits [[`d523eb9c40`](https://github.com/nodejs/node/commit/d523eb9c40)] [#11447](https://github.com/nodejs/node/pull/11447). * **URL** * The WHATWG URL implementation is now a fully-supported Node.js API [[`d080ead0f9`](https://github.com/nodejs/node/commit/d080ead0f9)] [#12710](https://github.com/nodejs/node/pull/12710). * **Util** * `Symbol` keys are now displayed by default when using `util.inspect()` [[`5bfd13b81e`](https://github.com/nodejs/node/commit/5bfd13b81e)] [#9726](https://github.com/nodejs/node/pull/9726). * `toJSON` errors will be thrown when formatting `%j` [[`455e6f1dd8`](https://github.com/nodejs/node/commit/455e6f1dd8)] [#11708](https://github.com/nodejs/node/pull/11708). * Convert `inspect.styles` and `inspect.colors` to prototype-less objects [[`aab0d202f8`](https://github.com/nodejs/node/commit/aab0d202f8)] [#11624](https://github.com/nodejs/node/pull/11624). * The new `util.promisify()` API has been added [[`99da8e8e02`](https://github.com/nodejs/node/commit/99da8e8e02)] [#12442](https://github.com/nodejs/node/pull/12442). * **Zlib** * Support `Uint8Array` in Zlib convenience methods [[`91383e47fd`](https://github.com/nodejs/node/commit/91383e47fd)] [#12001](https://github.com/nodejs/node/pull/12001). * Zlib errors now use `RangeError` and `TypeError` consistently [[`b514bd231e`](https://github.com/nodejs/node/commit/b514bd231e)] [#11391](https://github.com/nodejs/node/pull/11391).
2017-03-16 04:26:14 +01:00
- version: v8.0.0
pr-url: https://github.com/nodejs/node/pull/11608
description: The `chunk` argument can now be a `Uint8Array` instance.
- version: v6.0.0
pr-url: https://github.com/nodejs/node/pull/6170
description: Passing `null` as the `chunk` parameter will always be
considered invalid now, even in object mode.
-->
* `chunk` {string|Buffer|Uint8Array|any} Optional data to write. For streams
not operating in object mode, `chunk` must be a string, `Buffer` or
`Uint8Array`. For object mode streams, `chunk` may be any JavaScript value
other than `null`.
* `encoding` {string} The encoding, if `chunk` is a string. **Default:** `'utf8'`
* `callback` {Function} Callback for when this chunk of data is flushed
* Returns: {boolean} `false` if the stream wishes for the calling code to
wait for the `'drain'` event to be emitted before continuing to write
additional data; otherwise `true`.
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` *may or may not* be called with the error as its
first argument. To reliably detect write errors, add a listener for the
`'error'` event. The `callback` is called asynchronously and before `'error'` is
emitted.
The return value is `true` if the internal buffer is less than the
`highWaterMark` configured when the stream was created after admitting `chunk`.
If `false` is returned, further attempts to write data to the stream should
stop until the [`'drain'`][] event is emitted.
While a stream is not draining, calls to `write()` will buffer `chunk`, and
return false. Once all currently buffered chunks are drained (accepted for
delivery by the operating system), the `'drain'` event will be emitted.
It is recommended that once `write()` returns false, no more chunks be written
until the `'drain'` event is emitted. While calling `write()` on a stream that
is not draining is allowed, Node.js will buffer all written chunks until
maximum memory usage occurs, at which point it will abort unconditionally.
Even before it aborts, high memory usage will cause poor garbage collector
performance and high RSS (which is not typically released back to the system,
even after the memory is no longer required). Since TCP sockets may never
drain if the remote peer does not read the data, writing a socket that is
not draining may lead to a remotely exploitable vulnerability.
Writing data while the stream is not draining is particularly
problematic for a [`Transform`][], because the `Transform` streams are paused
by default until they are piped or a `'data'` or `'readable'` event handler
is added.
If the data to be written can be generated or fetched on demand, it is
recommended to encapsulate the logic into a [`Readable`][] and use
[`stream.pipe()`][]. However, if calling `write()` is preferred, it is
possible to respect backpressure and avoid memory issues using the
[`'drain'`][] event:
```js
function write(data, cb) {
if (!stream.write(data)) {
stream.once('drain', cb);
} else {
process.nextTick(cb);
}
}
// Wait for cb to be called before doing any other write.
write('hello', () => {
console.log('Write completed, do more writes now.');
});
```
A `Writable` stream in object mode will always ignore the `encoding` argument.
### Readable streams
Readable streams are an abstraction for a *source* from which data is
consumed.
Examples of `Readable` streams include:
* [HTTP responses, on the client][http-incoming-message]
* [HTTP requests, on the server][http-incoming-message]
* [fs read streams][]
* [zlib streams][zlib]
* [crypto streams][crypto]
* [TCP sockets][]
* [child process stdout and stderr][]
* [`process.stdin`][]
All [`Readable`][] streams implement the interface defined by the
`stream.Readable` class.
#### Two reading modes
`Readable` streams effectively operate in one of two modes: flowing and
paused. These modes are separate from [object mode][object-mode].
A [`Readable`][] stream can be in object mode or not, regardless of whether
it is in flowing mode or paused mode.
* In flowing mode, data is read from the underlying system automatically
and provided to an application as quickly as possible using events via the
[`EventEmitter`][] interface.
* In paused mode, the [`stream.read()`][stream-read] method must be called
explicitly to read chunks of data from the stream.
All [`Readable`][] streams begin in paused mode but can be switched to flowing
mode in one of the following ways:
* Adding a [`'data'`][] event handler.
* Calling the [`stream.resume()`][stream-resume] method.
* Calling the [`stream.pipe()`][] method to send the data to a [`Writable`][].
The `Readable` can switch back to paused mode using one of the following:
* If there are no pipe destinations, by calling the
[`stream.pause()`][stream-pause] method.
* If there are pipe destinations, by removing all pipe destinations.
Multiple pipe destinations may be removed by calling the
[`stream.unpipe()`][] method.
The important concept to remember is that a `Readable` will not generate data
until a mechanism for either consuming or ignoring that data is provided. If
the consuming mechanism is disabled or taken away, the `Readable` will *attempt*
to stop generating the data.
For backward compatibility reasons, removing [`'data'`][] event handlers will
**not** automatically pause the stream. Also, if there are piped destinations,
then calling [`stream.pause()`][stream-pause] will not guarantee that the
stream 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
available to handle the data, that data will be lost. This can occur, for
instance, when the `readable.resume()` method is called without a listener
attached to the `'data'` event, or when a `'data'` event handler is removed
from the stream.
Adding a [`'readable'`][] event handler automatically make the stream to
stop flowing, and the data to be consumed via
[`readable.read()`][stream-read]. If the [`'readable'`][] event handler is
removed, then the stream will start flowing again if there is a
[`'data'`][] event handler.
#### 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.
Specifically, at any given point in time, every `Readable` is in one of three
possible states:
* `readable.readableFlowing === null`
* `readable.readableFlowing === false`
* `readable.readableFlowing === true`
When `readable.readableFlowing` is `null`, no mechanism for consuming the
stream's data is provided. Therefore, the stream will not generate data.
While in this state, attaching a listener for the `'data'` event, calling the
`readable.pipe()` method, or calling the `readable.resume()` method will switch
`readable.readableFlowing` to `true`, causing the `Readable` to begin actively
emitting events as data is generated.
Calling `readable.pause()`, `readable.unpipe()`, or receiving backpressure
will cause the `readable.readableFlowing` to be set as `false`,
temporarily halting the flowing of events but *not* halting the generation of
data. While in this state, attaching a listener for the `'data'` event
will not switch `readable.readableFlowing` to `true`.
```js
const { PassThrough, Writable } = require('stream');
const pass = new PassThrough();
const writable = new Writable();
pass.pipe(writable);
pass.unpipe(writable);
// readableFlowing is now false.
pass.on('data', (chunk) => { console.log(chunk.toString()); });
pass.write('ok'); // Will not emit 'data'.
pass.resume(); // Must be called to make stream emit 'data'.
```
2012-12-13 20:15:49 +01:00
While `readable.readableFlowing` is `false`, data may be accumulating
within the stream's internal buffer.
#### 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. Specifically, using a combination
of `on('data')`, `on('readable')`, `pipe()`, or async iterators could
lead to unintuitive behavior.
Use of the `readable.pipe()` method is recommended for most users as it has been
implemented to provide the easiest way of consuming stream data. Developers that
require more fine-grained control over the transfer and generation of data can
use the [`EventEmitter`][] and `readable.on('readable')`/`readable.read()`
or the `readable.pause()`/`readable.resume()` APIs.
#### Class: `stream.Readable`
<!-- YAML
added: v0.9.4
-->
<!--type=class-->
##### Event: `'close'`
<!-- YAML
added: v0.9.4
changes:
- version: v10.0.0
pr-url: https://github.com/nodejs/node/pull/18438
description: Add `emitClose` option to specify if `'close'` is emitted on
destroy.
-->
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.
A [`Readable`][] stream will always emit the `'close'` event if it is
created with the `emitClose` option.
##### Event: `'data'`
<!-- YAML
added: v0.9.4
-->
* `chunk` {Buffer|string|any} The chunk of data. For streams that are not
operating in object mode, the chunk will be either a string or `Buffer`.
For streams that are in object mode, the chunk can be any JavaScript value
other than `null`.
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. The `'data'` event will
also be emitted whenever the `readable.read()` method is called and a chunk of
data is available to be returned.
Attaching a `'data'` event listener to a stream that has not been explicitly
paused will switch the stream into flowing mode. Data will then be passed as
soon as it is available.
The listener callback will be passed the chunk of data as a string if a default
encoding has been specified for the stream using the
`readable.setEncoding()` method; otherwise the data will be passed as a
`Buffer`.
```js
const readable = getReadableStreamSomehow();
readable.on('data', (chunk) => {
console.log(`Received ${chunk.length} bytes of data.`);
});
2012-12-13 20:15:49 +01:00
```
##### Event: `'end'`
<!-- YAML
added: v0.9.4
-->
2012-12-13 20:15:49 +01:00
The `'end'` event is emitted when there is no more data to be consumed from
the stream.
2010-10-28 14:18:16 +02:00
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()`][stream-read] repeatedly until all data has been
consumed.
2012-02-27 20:09:34 +01:00
```js
const readable = getReadableStreamSomehow();
readable.on('data', (chunk) => {
console.log(`Received ${chunk.length} bytes of data.`);
});
readable.on('end', () => {
console.log('There will be no more data.');
});
```
2010-10-28 14:18:16 +02:00
##### Event: `'error'`
<!-- YAML
added: v0.9.4
-->
2010-10-28 14:18:16 +02:00
* {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.
The listener callback will be passed a single `Error` object.
2010-10-28 14:18:16 +02:00
##### Event: `'pause'`
<!-- YAML
added: v0.9.4
-->
The `'pause'` event is emitted when [`stream.pause()`][stream-pause] is called
and `readableFlowing` is not `false`.
##### Event: `'readable'`
<!-- YAML
added: v0.9.4
changes:
2018-04-24, Version 10.0.0 (Current) * Assert * Calling `assert.fail()` with more than one argument is deprecated. #70dcacd710 * Calling `assert.ok()` with no arguments will now throw. #3cd7977a42 * Calling `assert.ifError()` will now throw with any argument other than `undefined` or `null`. Previously the method would throw with any truthy value. #e65a6e81ef * The `assert.rejects()` and `assert.doesNotReject()` methods have been added for working with async functions. #599337f43e * Async_hooks * Older experimental async_hooks APIs have been removed. #1cc6b993b9 * Buffer * Uses of `new Buffer()` and `Buffer()` outside of the `node_modules` directory will now emit a runtime deprecation warning. #9d4ab90117 * `Buffer.isEncoding()` now returns `undefined` for falsy values, including an empty string. #452eed956e * `Buffer.fill()` will throw if an attempt is made to fill with an empty `Buffer`. #1e802539b2 * Child Process * Undefined properties of env are ignored. #38ee25e2e2, #85739b6c5b * Console * The `console.table()` method has been added. #97ace04492 * Crypto * The `crypto.createCipher()` and `crypto.createDecipher()` methods have been deprecated. Please use `crypto.createCipheriv()` and `crypto.createDecipheriv()` instead. #81f88e30dd * The `decipher.finaltol()` method has been deprecated. #19f3927d92 * The `crypto.DEFAULT_ENCODING` property has been deprecated. #6035beea93 * The `ECDH.convertKey()` method has been added. #f2e02883e7 * The `crypto.fips` property has been deprecated. #6e7992e8b8 * Dependencies * V8 has been updated to 6.6. #9daebb48d6 * OpenSSL has been updated to 1.1.0h. #66cb29e646 * EventEmitter * The `EventEmitter.prototype.off()` method has been added as an alias for `EventEmitter.prototype.removeListener()`. #3bb6f07d52 * File System * The `fs.promises` API provides experimental promisified versions of the `fs` functions. #329fc78e49 * Invalid path errors are now thrown synchronously. #d8f73385e2 * The `fs.readFile()` method now partitions reads to avoid thread pool exhaustion. #67a4ce1c6e * HTTP * Processing of HTTP Status codes `100`, `102-199` has been improved. #baf8495078 * Multi-byte characters in URL paths are now forbidden. #b961d9fd83 * N-API * The n-api is no longer experimental. #cd7d7b15c1 * Net * The `'close'` event will be emitted after `'end'`. #9b7a6914a7 * Perf_hooks * The `PerformanceObserver` class is now an `AsyncResource` and can be monitored using `async_hooks`. #009e41826f * Trace events are now emitted for performance events. #9e509b622b * The `performance` API has been simplified. #2ec6995555 * Performance milestone marks will be emitted as trace events. #96cb4fb795 * Process * Using non-string values for `process.env` is deprecated. #5826fe4e79 * The `process.assert()` method is deprecated. #703e37cf3f * REPL * REPL now experimentally supports top-level await when using the `--experimental-repl-await` flag. #eeab7bc068 * The previously deprecated "magic mode" has been removed. #4893f70d12 * The previously deprecated `NODE_REPL_HISTORY_FILE` environment variable has been removed. #60c9ad7979 * Proxy objects are shown as Proxy objects when inspected. #90a43906ab * Streams * The `'readable'` event is now always deferred with nextTick. #1e0f3315c7 * A new `pipeline()` method has been provided for building end-to-data stream pipelines. #a5cf3feaf1 * Experimental support for async for-await has been added to `stream.Readable`. #61b4d60c5d * Timers * The `enroll()` and `unenroll()` methods have been deprecated. #68783ae0b8 * TLS * The `tls.convertNONProtocols()` method has been deprecated. #9204a0db6e * Support for NPN (next protocol negotiation) has been dropped. #5bfbe5ceae * The `ecdhCurve` default is now `'auto'`. #af78840b19 * Trace Events * A new `trace_events` top-level module allows trace event categories to be enabled/disabld at runtime. #da5d818a54 * URL * The WHATWG URL API is now a global. #312414662b * Util * `util.types.is[…]` type checks have been added. #b20af8088a * Support for bigint formatting has been added to `util.inspect()`. #39dc947409
2018-03-02 18:53:46 +01:00
- version: v10.0.0
pr-url: https://github.com/nodejs/node/pull/17979
description: The `'readable'` is always emitted in the next tick after
`.push()` is called.
2018-04-24, Version 10.0.0 (Current) * Assert * Calling `assert.fail()` with more than one argument is deprecated. #70dcacd710 * Calling `assert.ok()` with no arguments will now throw. #3cd7977a42 * Calling `assert.ifError()` will now throw with any argument other than `undefined` or `null`. Previously the method would throw with any truthy value. #e65a6e81ef * The `assert.rejects()` and `assert.doesNotReject()` methods have been added for working with async functions. #599337f43e * Async_hooks * Older experimental async_hooks APIs have been removed. #1cc6b993b9 * Buffer * Uses of `new Buffer()` and `Buffer()` outside of the `node_modules` directory will now emit a runtime deprecation warning. #9d4ab90117 * `Buffer.isEncoding()` now returns `undefined` for falsy values, including an empty string. #452eed956e * `Buffer.fill()` will throw if an attempt is made to fill with an empty `Buffer`. #1e802539b2 * Child Process * Undefined properties of env are ignored. #38ee25e2e2, #85739b6c5b * Console * The `console.table()` method has been added. #97ace04492 * Crypto * The `crypto.createCipher()` and `crypto.createDecipher()` methods have been deprecated. Please use `crypto.createCipheriv()` and `crypto.createDecipheriv()` instead. #81f88e30dd * The `decipher.finaltol()` method has been deprecated. #19f3927d92 * The `crypto.DEFAULT_ENCODING` property has been deprecated. #6035beea93 * The `ECDH.convertKey()` method has been added. #f2e02883e7 * The `crypto.fips` property has been deprecated. #6e7992e8b8 * Dependencies * V8 has been updated to 6.6. #9daebb48d6 * OpenSSL has been updated to 1.1.0h. #66cb29e646 * EventEmitter * The `EventEmitter.prototype.off()` method has been added as an alias for `EventEmitter.prototype.removeListener()`. #3bb6f07d52 * File System * The `fs.promises` API provides experimental promisified versions of the `fs` functions. #329fc78e49 * Invalid path errors are now thrown synchronously. #d8f73385e2 * The `fs.readFile()` method now partitions reads to avoid thread pool exhaustion. #67a4ce1c6e * HTTP * Processing of HTTP Status codes `100`, `102-199` has been improved. #baf8495078 * Multi-byte characters in URL paths are now forbidden. #b961d9fd83 * N-API * The n-api is no longer experimental. #cd7d7b15c1 * Net * The `'close'` event will be emitted after `'end'`. #9b7a6914a7 * Perf_hooks * The `PerformanceObserver` class is now an `AsyncResource` and can be monitored using `async_hooks`. #009e41826f * Trace events are now emitted for performance events. #9e509b622b * The `performance` API has been simplified. #2ec6995555 * Performance milestone marks will be emitted as trace events. #96cb4fb795 * Process * Using non-string values for `process.env` is deprecated. #5826fe4e79 * The `process.assert()` method is deprecated. #703e37cf3f * REPL * REPL now experimentally supports top-level await when using the `--experimental-repl-await` flag. #eeab7bc068 * The previously deprecated "magic mode" has been removed. #4893f70d12 * The previously deprecated `NODE_REPL_HISTORY_FILE` environment variable has been removed. #60c9ad7979 * Proxy objects are shown as Proxy objects when inspected. #90a43906ab * Streams * The `'readable'` event is now always deferred with nextTick. #1e0f3315c7 * A new `pipeline()` method has been provided for building end-to-data stream pipelines. #a5cf3feaf1 * Experimental support for async for-await has been added to `stream.Readable`. #61b4d60c5d * Timers * The `enroll()` and `unenroll()` methods have been deprecated. #68783ae0b8 * TLS * The `tls.convertNONProtocols()` method has been deprecated. #9204a0db6e * Support for NPN (next protocol negotiation) has been dropped. #5bfbe5ceae * The `ecdhCurve` default is now `'auto'`. #af78840b19 * Trace Events * A new `trace_events` top-level module allows trace event categories to be enabled/disabld at runtime. #da5d818a54 * URL * The WHATWG URL API is now a global. #312414662b * Util * `util.types.is[…]` type checks have been added. #b20af8088a * Support for bigint formatting has been added to `util.inspect()`. #39dc947409
2018-03-02 18:53:46 +01:00
- version: v10.0.0
pr-url: https://github.com/nodejs/node/pull/18994
description: Using `'readable'` requires calling `.read()`.
-->
2012-12-13 20:15:49 +01:00
The `'readable'` event is emitted when there is data available to be read from
the stream. In some cases, attaching a listener for the `'readable'` event will
cause some amount of data to be read into an internal buffer.
```js
const readable = getReadableStreamSomehow();
readable.on('readable', function() {
// There is some data to read now.
let data;
while (data = this.read()) {
console.log(data);
}
});
```
The `'readable'` event will also be emitted once the end of the stream data
has been reached but before the `'end'` event is emitted.
Effectively, the `'readable'` event indicates that the stream has new
information: either new data is available or the end of the stream has been
reached. In the former case, [`stream.read()`][stream-read] will return the
available data. In the latter case, [`stream.read()`][stream-read] will return
`null`. For instance, in the following example, `foo.txt` is an empty file:
```js
const fs = require('fs');
const rr = fs.createReadStream('foo.txt');
rr.on('readable', () => {
console.log(`readable: ${rr.read()}`);
});
rr.on('end', () => {
console.log('end');
});
```
The output of running this script is:
```console
$ node test.js
readable: null
end
```
In general, the `readable.pipe()` and `'data'` event mechanisms are easier to
understand than the `'readable'` event. However, handling `'readable'` might
result in increased throughput.
If both `'readable'` and [`'data'`][] are used at the same time, `'readable'`
takes precedence in controlling the flow, i.e. `'data'` will be emitted
only when [`stream.read()`][stream-read] is called. The
`readableFlowing` property would become `false`.
If there are `'data'` listeners when `'readable'` is removed, the stream
will start flowing, i.e. `'data'` events will be emitted without calling
`.resume()`.
##### Event: `'resume'`
<!-- YAML
added: v0.9.4
-->
The `'resume'` event is emitted when [`stream.resume()`][stream-resume] is
called and `readableFlowing` is not `true`.
##### `readable.destroy([error])`
<!-- YAML
added: v8.0.0
-->
* `error` {Error} Error which will be passed as payload in `'error'` event
* Returns: {this}
Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'`
event (unless `emitClose` is set to `false`). After this call, the readable
stream will release any internal resources and subsequent calls to `push()`
will be ignored.
Once `destroy()` has been called any further calls will be a noop and no
further errors except from `_destroy` may be emitted as `'error'`.
Implementors should not override this method, but instead implement
[`readable._destroy()`][readable-_destroy].
##### `readable.destroyed`
<!-- YAML
added: v8.0.0
-->
* {boolean}
Is `true` after [`readable.destroy()`][readable-destroy] has been called.
##### `readable.isPaused()`
<!-- YAML
added: v0.11.14
-->
* Returns: {boolean}
The `readable.isPaused()` method returns the current operating state of the
`Readable`. This is used primarily by the mechanism that underlies the
`readable.pipe()` method. In most typical cases, there will be no reason to
use this method directly.
```js
const readable = new stream.Readable();
readable.isPaused(); // === false
readable.pause();
readable.isPaused(); // === true
readable.resume();
readable.isPaused(); // === false
```
##### `readable.pause()`
<!-- YAML
added: v0.9.4
-->
* 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.
```js
const readable = getReadableStreamSomehow();
readable.on('data', (chunk) => {
console.log(`Received ${chunk.length} bytes of data.`);
readable.pause();
console.log('There will be no additional data for 1 second.');
setTimeout(() => {
console.log('Now data will start flowing again.');
readable.resume();
}, 1000);
});
```
The `readable.pause()` method has no effect if there is a `'readable'`
event listener.
##### `readable.pipe(destination[, options])`
<!-- YAML
added: v0.9.4
-->
* `destination` {stream.Writable} The destination for writing data
* `options` {Object} Pipe options
* `end` {boolean} End the writer when the reader ends. **Default:** `true`.
* Returns: {stream.Writable} The *destination*, allowing for a chain of pipes if
it is a [`Duplex`][] or a [`Transform`][] stream
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`][]. The flow of data will be automatically managed
so that the destination `Writable` stream is not overwhelmed by a faster
`Readable` stream.
The following example pipes all of the data from the `readable` into a file
named `file.txt`:
```js
const fs = require('fs');
const readable = getReadableStreamSomehow();
const writable = fs.createWriteStream('file.txt');
// All the data from readable goes into 'file.txt'.
readable.pipe(writable);
```
It is possible to attach multiple `Writable` streams to a single `Readable`
stream.
2012-12-13 20:15:49 +01:00
The `readable.pipe()` method returns a reference to the *destination* stream
making it possible to set up chains of piped streams:
```js
const fs = require('fs');
const r = fs.createReadStream('file.txt');
const z = zlib.createGzip();
const w = fs.createWriteStream('file.txt.gz');
r.pipe(z).pipe(w);
```
By default, [`stream.end()`][stream-end] is called on the destination `Writable`
stream when the source `Readable` stream emits [`'end'`][], so that the
destination is no longer writable. To disable this default behavior, the `end`
option can be passed as `false`, causing the destination stream to remain open:
```js
reader.pipe(writer, { end: false });
reader.on('end', () => {
writer.end('Goodbye\n');
});
```
One important caveat is that if the `Readable` stream emits an error during
processing, the `Writable` destination *is not closed* automatically. If an
error occurs, it will be necessary to *manually* close each stream in order
to prevent memory leaks.
The [`process.stderr`][] and [`process.stdout`][] `Writable` streams are never
closed until the Node.js process exits, regardless of the specified options.
##### `readable.read([size])`
<!-- YAML
added: v0.9.4
-->
* `size` {number} Optional argument to specify how much data to read.
* Returns: {string|Buffer|null|any}
The `readable.read()` method pulls some data out of the internal buffer and
returns it. If no data available to be read, `null` is returned. By default,
the data will be returned as a `Buffer` object unless an encoding has been
specified using the `readable.setEncoding()` method or the stream is operating
in object mode.
The optional `size` argument specifies a specific number of bytes to read. If
`size` bytes are not available to be read, `null` will be returned *unless*
the stream has ended, in which case all of the data remaining in the internal
buffer will be returned.
stream: Fix unshift() race conditions Fix #5272 The consumption of a readable stream is a dance with 3 partners. 1. The specific stream Author (A) 2. The Stream Base class (B), and 3. The Consumer of the stream (C) When B calls the _read() method that A implements, it sets a 'reading' flag, so that parallel calls to _read() can be avoided. When A calls stream.push(), B knows that it's safe to start calling _read() again. If the consumer C is some kind of parser that wants in some cases to pass the source stream off to some other party, but not before "putting back" some bit of previously consumed data (as in the case of Node's websocket http upgrade implementation). So, stream.unshift() will generally *never* be called by A, but *only* called by C. Prior to this patch, stream.unshift() *also* unset the state.reading flag, meaning that C could indicate the end of a read, and B would dutifully fire off another _read() call to A. This is inappropriate. In the case of fs streams, and other variably-laggy streams that don't tolerate overlapped _read() calls, this causes big problems. Also, calling stream.shift() after the 'end' event did not raise any kind of error, but would cause very strange behavior indeed. Calling it after the EOF chunk was seen, but before the 'end' event was fired would also cause weird behavior, and could lead to data being lost, since it would not emit another 'readable' event. This change makes it so that: 1. stream.unshift() does *not* set state.reading = false 2. stream.unshift() is allowed up until the 'end' event. 3. unshifting onto a EOF-encountered and zero-length (but not yet end-emitted) stream will defer the 'end' event until the new data is consumed. 4. pushing onto a EOF-encountered stream is now an error. So, if you read(), you have that single tick to safely unshift() data back into the stream, even if the null chunk was pushed, and the length was 0.
2013-04-12 00:01:26 +02:00
If the `size` argument is not specified, all of the data contained in the
internal buffer will be returned.
The `size` argument must be less than or equal to 1 GB.
The `readable.read()` method should only be called on `Readable` streams
operating in paused mode. In flowing mode, `readable.read()` is called
automatically until the internal buffer is fully drained.
```js
const readable = getReadableStreamSomehow();
readable.on('readable', () => {
let chunk;
while (null !== (chunk = readable.read())) {
console.log(`Received ${chunk.length} bytes of data.`);
}
});
```
The `while` loop is necessary when processing data with
`readable.read()`. Only after `readable.read()` returns `null`,
[`'readable'`][] will be emitted.
A `Readable` stream in object mode will always return a single item from
a call to [`readable.read(size)`][stream-read], regardless of the value of the
`size` argument.
If the `readable.read()` method returns a chunk of data, a `'data'` event will
also be emitted.
Calling [`stream.read([size])`][stream-read] after the [`'end'`][] event has
been emitted will return `null`. No runtime error will be raised.
##### `readable.readable`
<!-- YAML
added: v11.4.0
-->
* {boolean}
Is `true` if it is safe to call [`readable.read()`][stream-read], which means
the stream has not been destroyed or emitted `'error'` or `'end'`.
##### `readable.readableEncoding`
<!-- YAML
2019-07-23, Version 12.7.0 (Current) Notable changes: * deps: * Updated nghttp2 to 1.39.1. https://github.com/nodejs/node/pull/28448 * Updated npm to 6.10.0. https://github.com/nodejs/node/pull/28525 * esm: * Implemented experimental "pkg-exports" proposal. A new `"exports"` field can be added to a module's `package.json` file to provide custom subpath aliasing. See https://github.com/jkrems/proposal-pkg-exports/ for more information. https://github.com/nodejs/node/pull/28568 * http: * Added `response.writableFinished`. https://github.com/nodejs/node/pull/28681 * Exposed `headers`, `rawHeaders` and other fields on an `http.ClientRequest` `"information"` event. https://github.com/nodejs/node/pull/28459 * inspector: * Added `inspector.waitForDebugger()`. https://github.com/nodejs/node/pull/28453 * policy: * Added `--policy-integrity=sri` CLI option to mitigate policy tampering. If a policy integrity is specified and the policy does not have that integrity, Node.js will error prior to running any code. https://github.com/nodejs/node/pull/28734 * readline,tty: * Exposed stream API from various methods which write characters. https://github.com/nodejs/node/pull/28674 https://github.com/nodejs/node/pull/28721 * src: * Use cgroups to get memory limits. This improves the way we set the memory ceiling for a Node.js process. Previously we would use the physical memory size to estimate the necessary V8 heap sizes. The physical memory size is not necessarily the correct limit, e.g. if the process is running inside a docker container or is otherwise constrained. This change adds the ability to get a memory limit set by linux cgroups, which is used by docker containers to set resource constraints. https://docs.docker.com/config/containers/resource_constraints/ https://github.com/nodejs/node/pull/27508 PR-URL: https://github.com/nodejs/node/pull/28817
2019-07-23 10:29:14 +02:00
added: v12.7.0
-->
* {null|string}
Getter for the property `encoding` of a given `Readable` stream. The `encoding`
property can be set using the [`readable.setEncoding()`][] method.
##### `readable.readableEnded`
<!-- YAML
2019-08-20, Version 12.9.0 (Current) Notable changes: * crypto: * Added an oaepHash option to asymmetric encryption which allows users to specify a hash function when using OAEP padding. https://github.com/nodejs/node/pull/28335 * deps: * Updated V8 to 7.6.303.29. https://github.com/nodejs/node/pull/28955 * Improves the performance of various APIs such as `JSON.parse` and methods called on frozen arrays. * Adds the Promise.allSettled method. * Improves support of `BigInt` in `Intl` methods. * For more information: https://v8.dev/blog/v8-release-76 * Updated libuv to 1.31.0. https://github.com/nodejs/node/pull/29070 * `UV_FS_O_FILEMAP` has been added for faster access to memory mapped files on Windows. * `uv_fs_mkdir()` now returns `UV_EINVAL` for invalid filenames on Windows. It previously returned `UV_ENOENT`. * The `uv_fs_statfs()` API has been added. * The `uv_os_environ()` and `uv_os_free_environ()` APIs have been added. * fs: * Added `fs.writev`, `fs.writevSync` and `filehandle.writev` (promise version) methods. They allow to write an array of `ArrayBufferView`s to a file descriptor. https://github.com/nodejs/node/pull/25925 https://github.com/nodejs/node/pull/29186 * http: * Added three properties to `OutgoingMessage.prototype`: `writableObjectMode`, `writableLength` and `writableHighWaterMark` https://github.com/nodejs/node/pull/29018 * stream: * Added an new property `readableEnded` to readable streams. Its value is set to `true` when the `'end'` event is emitted. https://github.com/nodejs/node/pull/28814 * Added an new property `writableEnded` to writable streams. Its value is set to `true` after `writable.end()` has been called. https://github.com/nodejs/node/pull/28934 PR-URL: https://github.com/nodejs/node/pull/29210
2019-08-19 21:14:22 +02:00
added: v12.9.0
-->
* {boolean}
Becomes `true` when [`'end'`][] event is emitted.
##### `readable.readableFlowing`
<!-- YAML
added: v9.4.0
-->
* {boolean}
This property reflects the current state of a `Readable` stream as described
in the [Three states][] section.
##### `readable.readableHighWaterMark`
<!-- YAML
added: v9.3.0
-->
* {number}
Returns the value of `highWaterMark` passed when creating this `Readable`.
##### `readable.readableLength`
<!-- YAML
2019-01-10 Version 9.4.0 (Current) Notable change: * async_hooks: - deprecate AsyncHooks Sensitive API and runInAsyncIdScope. Neither API were documented. (Andreas Madsen) https://github.com/nodejs/node/pull/16972 * deps: - update nghttp2 to 1.29.0 (James M Snell) https://github.com/nodejs/node/pull/17908 - upgrade npm to 5.6.0 (Kat Marchán) https://github.com/nodejs/node/pull/17535 - cherry-pick 50f7455 from upstream V8 (Michaël Zasso) https://github.com/nodejs/node/pull/16591 * events: - remove reaches into _events internals (Anatoli Papirovski) https://github.com/nodejs/node/pull/17440 * http: - add rawPacket in err of `clientError` event (XadillaX) https://github.com/nodejs/node/pull/17672 * http2: - implement maxSessionMemory (James M Snell) https://github.com/nodejs/node/pull/17967 - add initial support for originSet (James M Snell) https://github.com/nodejs/node/pull/17935 - add altsvc support (James M Snell) https://github.com/nodejs/node/pull/17917 - perf_hooks integration (James M Snell) https://github.com/nodejs/node/pull/17906 - Refactoring and cleanup of Http2Session and Http2Stream destroy (James M Snell) https://github.com/nodejs/node/pull/17406 * net: - remove Socket.prototype.write (Anna Henningsen) https://github.com/nodejs/node/pull/17644 - remove Socket.prototype.listen (Ruben Bridgewater) https://github.com/nodejs/node/pull/13735 * repl: - show lexically scoped vars in tab completion (Michaël Zasso) https://github.com/nodejs/node/pull/16591 * stream: - rm {writeable/readable}State.length (Calvin Metcalf) https://github.com/nodejs/node/pull/12857 - add flow and buffer properties to streams (Calvin Metcalf) https://github.com/nodejs/node/pull/12855 * util: - allow wildcards in NODE_DEBUG variable (Tyler) https://github.com/nodejs/node/pull/17609 * zlib: - add ArrayBuffer support (Jem Bezooyen) https://github.com/nodejs/node/pull/16042 * Addedew collaborator** - [starkwang](https://github.com/starkwang) Weijia Wang * Addedew TSC member** - [danbev](https://github.com/danbev) Daniel Bevenius PR-URL: https://github.com/nodejs/node/pull/18069
2018-01-10 01:23:55 +01:00
added: v9.4.0
-->
* {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`.
##### `readable.readableObjectMode`
<!-- YAML
added: v12.3.0
-->
* {boolean}
Getter for the property `objectMode` of a given `Readable` stream.
##### `readable.resume()`
<!-- YAML
added: v0.9.4
changes:
2018-04-24, Version 10.0.0 (Current) * Assert * Calling `assert.fail()` with more than one argument is deprecated. #70dcacd710 * Calling `assert.ok()` with no arguments will now throw. #3cd7977a42 * Calling `assert.ifError()` will now throw with any argument other than `undefined` or `null`. Previously the method would throw with any truthy value. #e65a6e81ef * The `assert.rejects()` and `assert.doesNotReject()` methods have been added for working with async functions. #599337f43e * Async_hooks * Older experimental async_hooks APIs have been removed. #1cc6b993b9 * Buffer * Uses of `new Buffer()` and `Buffer()` outside of the `node_modules` directory will now emit a runtime deprecation warning. #9d4ab90117 * `Buffer.isEncoding()` now returns `undefined` for falsy values, including an empty string. #452eed956e * `Buffer.fill()` will throw if an attempt is made to fill with an empty `Buffer`. #1e802539b2 * Child Process * Undefined properties of env are ignored. #38ee25e2e2, #85739b6c5b * Console * The `console.table()` method has been added. #97ace04492 * Crypto * The `crypto.createCipher()` and `crypto.createDecipher()` methods have been deprecated. Please use `crypto.createCipheriv()` and `crypto.createDecipheriv()` instead. #81f88e30dd * The `decipher.finaltol()` method has been deprecated. #19f3927d92 * The `crypto.DEFAULT_ENCODING` property has been deprecated. #6035beea93 * The `ECDH.convertKey()` method has been added. #f2e02883e7 * The `crypto.fips` property has been deprecated. #6e7992e8b8 * Dependencies * V8 has been updated to 6.6. #9daebb48d6 * OpenSSL has been updated to 1.1.0h. #66cb29e646 * EventEmitter * The `EventEmitter.prototype.off()` method has been added as an alias for `EventEmitter.prototype.removeListener()`. #3bb6f07d52 * File System * The `fs.promises` API provides experimental promisified versions of the `fs` functions. #329fc78e49 * Invalid path errors are now thrown synchronously. #d8f73385e2 * The `fs.readFile()` method now partitions reads to avoid thread pool exhaustion. #67a4ce1c6e * HTTP * Processing of HTTP Status codes `100`, `102-199` has been improved. #baf8495078 * Multi-byte characters in URL paths are now forbidden. #b961d9fd83 * N-API * The n-api is no longer experimental. #cd7d7b15c1 * Net * The `'close'` event will be emitted after `'end'`. #9b7a6914a7 * Perf_hooks * The `PerformanceObserver` class is now an `AsyncResource` and can be monitored using `async_hooks`. #009e41826f * Trace events are now emitted for performance events. #9e509b622b * The `performance` API has been simplified. #2ec6995555 * Performance milestone marks will be emitted as trace events. #96cb4fb795 * Process * Using non-string values for `process.env` is deprecated. #5826fe4e79 * The `process.assert()` method is deprecated. #703e37cf3f * REPL * REPL now experimentally supports top-level await when using the `--experimental-repl-await` flag. #eeab7bc068 * The previously deprecated "magic mode" has been removed. #4893f70d12 * The previously deprecated `NODE_REPL_HISTORY_FILE` environment variable has been removed. #60c9ad7979 * Proxy objects are shown as Proxy objects when inspected. #90a43906ab * Streams * The `'readable'` event is now always deferred with nextTick. #1e0f3315c7 * A new `pipeline()` method has been provided for building end-to-data stream pipelines. #a5cf3feaf1 * Experimental support for async for-await has been added to `stream.Readable`. #61b4d60c5d * Timers * The `enroll()` and `unenroll()` methods have been deprecated. #68783ae0b8 * TLS * The `tls.convertNONProtocols()` method has been deprecated. #9204a0db6e * Support for NPN (next protocol negotiation) has been dropped. #5bfbe5ceae * The `ecdhCurve` default is now `'auto'`. #af78840b19 * Trace Events * A new `trace_events` top-level module allows trace event categories to be enabled/disabld at runtime. #da5d818a54 * URL * The WHATWG URL API is now a global. #312414662b * Util * `util.types.is[…]` type checks have been added. #b20af8088a * Support for bigint formatting has been added to `util.inspect()`. #39dc947409
2018-03-02 18:53:46 +01:00
- version: v10.0.0
pr-url: https://github.com/nodejs/node/pull/18994
description: The `resume()` has no effect if there is a `'readable'` event
listening.
-->
* Returns: {this}
The `readable.resume()` method causes an explicitly paused `Readable` stream to
resume emitting [`'data'`][] events, switching the stream into flowing mode.
The `readable.resume()` method can be used to fully consume the data from a
stream without actually processing any of that data:
```js
getReadableStreamSomehow()
.resume()
.on('end', () => {
console.log('Reached the end, but did not read anything.');
});
```
The `readable.resume()` method has no effect if there is a `'readable'`
event listener.
##### `readable.setEncoding(encoding)`
<!-- YAML
added: v0.9.4
-->
* `encoding` {string} The encoding to use.
* Returns: {this}
The `readable.setEncoding()` method sets the character encoding for
data read from the `Readable` stream.
By default, no encoding is assigned and stream data will be returned as
`Buffer` objects. Setting an encoding causes the stream data
to be returned as strings of the specified encoding rather than as `Buffer`
objects. For instance, calling `readable.setEncoding('utf8')` will cause the
output data to be interpreted as UTF-8 data, and passed as strings. Calling
`readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal
string format.
The `Readable` stream will properly handle multi-byte characters delivered
through the stream that would otherwise become improperly decoded if simply
pulled from the stream as `Buffer` objects.
```js
const readable = getReadableStreamSomehow();
readable.setEncoding('utf8');
readable.on('data', (chunk) => {
assert.equal(typeof chunk, 'string');
console.log('Got %d characters of string data:', chunk.length);
});
```
##### `readable.unpipe([destination])`
<!-- YAML
added: v0.9.4
-->
* `destination` {stream.Writable} Optional specific stream to unpipe
* Returns: {this}
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.
```js
const fs = require('fs');
const readable = getReadableStreamSomehow();
const writable = fs.createWriteStream('file.txt');
// All the data from readable goes into 'file.txt',
// but only for the first second.
readable.pipe(writable);
setTimeout(() => {
console.log('Stop writing to file.txt.');
readable.unpipe(writable);
console.log('Manually close the file stream.');
writable.end();
}, 1000);
```
##### `readable.unshift(chunk[, encoding])`
<!-- YAML
added: v0.9.11
changes:
2017-05-30, Version 8.0.0 (Current) * **Async Hooks** * The `async_hooks` module has landed in core [[`4a7233c178`](https://github.com/nodejs/node/commit/4a7233c178)] [#12892](https://github.com/nodejs/node/pull/12892). * **Buffer** * Using the `--pending-deprecation` flag will cause Node.js to emit a deprecation warning when using `new Buffer(num)` or `Buffer(num)`. [[`d2d32ea5a2`](https://github.com/nodejs/node/commit/d2d32ea5a2)] [#11968](https://github.com/nodejs/node/pull/11968). * `new Buffer(num)` and `Buffer(num)` will zero-fill new `Buffer` instances [[`7eb1b4658e`](https://github.com/nodejs/node/commit/7eb1b4658e)] [#12141](https://github.com/nodejs/node/pull/12141). * Many `Buffer` methods now accept `Uint8Array` as input [[`beca3244e2`](https://github.com/nodejs/node/commit/beca3244e2)] [#10236](https://github.com/nodejs/node/pull/10236). * **Child Process** * Argument and kill signal validations have been improved [[`97a77288ce`](https://github.com/nodejs/node/commit/97a77288ce)] [#12348](https://github.com/nodejs/node/pull/12348), [[`d75fdd96aa`](https://github.com/nodejs/node/commit/d75fdd96aa)] [#10423](https://github.com/nodejs/node/pull/10423). * Child Process methods accept `Uint8Array` as input [[`627ecee9ed`](https://github.com/nodejs/node/commit/627ecee9ed)] [#10653](https://github.com/nodejs/node/pull/10653). * **Console** * Error events emitted when using `console` methods are now supressed. [[`f18e08d820`](https://github.com/nodejs/node/commit/f18e08d820)] [#9744](https://github.com/nodejs/node/pull/9744). * **Dependencies** * The npm client has been updated to 5.0.0 [[`3c3b36af0f`](https://github.com/nodejs/node/commit/3c3b36af0f)] [#12936](https://github.com/nodejs/node/pull/12936). * V8 has been updated to 5.8 with forward ABI stability to 6.0 [[`60d1aac8d2`](https://github.com/nodejs/node/commit/60d1aac8d2)] [#12784](https://github.com/nodejs/node/pull/12784). * **Domains** * Native `Promise` instances are now `Domain` aware [[`84dabe8373`](https://github.com/nodejs/node/commit/84dabe8373)] [#12489](https://github.com/nodejs/node/pull/12489). * **Errors** * We have started assigning static error codes to errors generated by Node.js. This has been done through multiple commits and is still a work in progress. * **File System** * The utility class `fs.SyncWriteStream` has been deprecated [[`7a55e34ef4`](https://github.com/nodejs/node/commit/7a55e34ef4)] [#10467](https://github.com/nodejs/node/pull/10467). * The deprecated `fs.read()` string interface has been removed [[`3c2a9361ff`](https://github.com/nodejs/node/commit/3c2a9361ff)] [#9683](https://github.com/nodejs/node/pull/9683). * **HTTP** * Improved support for userland implemented Agents [[`90403dd1d0`](https://github.com/nodejs/node/commit/90403dd1d0)] [#11567](https://github.com/nodejs/node/pull/11567). * Outgoing Cookie headers are concatenated into a single string [[`d3480776c7`](https://github.com/nodejs/node/commit/d3480776c7)] [#11259](https://github.com/nodejs/node/pull/11259). * The `httpResponse.writeHeader()` method has been deprecated [[`fb71ba4921`](https://github.com/nodejs/node/commit/fb71ba4921)] [#11355](https://github.com/nodejs/node/pull/11355). * New methods for accessing HTTP headers have been added to `OutgoingMessage` [[`3e6f1032a4`](https://github.com/nodejs/node/commit/3e6f1032a4)] [#10805](https://github.com/nodejs/node/pull/10805). * **Lib** * All deprecation messages have been assigned static identifiers [[`5de3cf099c`](https://github.com/nodejs/node/commit/5de3cf099c)] [#10116](https://github.com/nodejs/node/pull/10116). * The legacy `linkedlist` module has been removed [[`84a23391f6`](https://github.com/nodejs/node/commit/84a23391f6)] [#12113](https://github.com/nodejs/node/pull/12113). * **N-API** * Experimental support for the new N-API API has been added [[`56e881d0b0`](https://github.com/nodejs/node/commit/56e881d0b0)] [#11975](https://github.com/nodejs/node/pull/11975). * **Process** * Process warning output can be redirected to a file using the `--redirect-warnings` command-line argument [[`03e89b3ff2`](https://github.com/nodejs/node/commit/03e89b3ff2)] [#10116](https://github.com/nodejs/node/pull/10116). * Process warnings may now include additional detail [[`dd20e68b0f`](https://github.com/nodejs/node/commit/dd20e68b0f)] [#12725](https://github.com/nodejs/node/pull/12725). * **REPL** * REPL magic mode has been deprecated [[`3f27f02da0`](https://github.com/nodejs/node/commit/3f27f02da0)] [#11599](https://github.com/nodejs/node/pull/11599). * **Src** * `NODE_MODULE_VERSION` has been updated to 57 (https://github.com/nodejs/node/commit/ec7cbaf266)] [#12995](https://github.com/nodejs/node/pull/12995). * Add `--pending-deprecation` command-line argument and `NODE_PENDING_DEPRECATION` environment variable [[`a16b570f8c`](https://github.com/nodejs/node/commit/a16b570f8c)] [#11968](https://github.com/nodejs/node/pull/11968). * The `--debug` command-line argument has been deprecated. Note that using `--debug` will enable the *new* Inspector-based debug protocol as the legacy Debugger protocol previously used by Node.js has been removed. [[`010f864426`](https://github.com/nodejs/node/commit/010f864426)] [#12949](https://github.com/nodejs/node/pull/12949). * Throw when the `-c` and `-e` command-line arguments are used at the same time [[`a5f91ab230`](https://github.com/nodejs/node/commit/a5f91ab230)] [#11689](https://github.com/nodejs/node/pull/11689). * Throw when the `--use-bundled-ca` and `--use-openssl-ca` command-line arguments are used at the same time. [[`8a7db9d4b5`](https://github.com/nodejs/node/commit/8a7db9d4b5)] [#12087](https://github.com/nodejs/node/pull/12087). * **Stream** * `Stream` now supports `destroy()` and `_destroy()` APIs [[`b6e1d22fa6`](https://github.com/nodejs/node/commit/b6e1d22fa6)] [#12925](https://github.com/nodejs/node/pull/12925). * `Stream` now supports the `_final()` API [[`07c7f198db`](https://github.com/nodejs/node/commit/07c7f198db)] [#12828](https://github.com/nodejs/node/pull/12828). * **TLS** * The `rejectUnauthorized` option now defaults to `true` [[`348cc80a3c`](https://github.com/nodejs/node/commit/348cc80a3c)] [#5923](https://github.com/nodejs/node/pull/5923). * The `tls.createSecurePair()` API now emits a runtime deprecation [[`a2ae08999b`](https://github.com/nodejs/node/commit/a2ae08999b)] [#11349](https://github.com/nodejs/node/pull/11349). * A runtime deprecation will now be emitted when `dhparam` is less than 2048 bits [[`d523eb9c40`](https://github.com/nodejs/node/commit/d523eb9c40)] [#11447](https://github.com/nodejs/node/pull/11447). * **URL** * The WHATWG URL implementation is now a fully-supported Node.js API [[`d080ead0f9`](https://github.com/nodejs/node/commit/d080ead0f9)] [#12710](https://github.com/nodejs/node/pull/12710). * **Util** * `Symbol` keys are now displayed by default when using `util.inspect()` [[`5bfd13b81e`](https://github.com/nodejs/node/commit/5bfd13b81e)] [#9726](https://github.com/nodejs/node/pull/9726). * `toJSON` errors will be thrown when formatting `%j` [[`455e6f1dd8`](https://github.com/nodejs/node/commit/455e6f1dd8)] [#11708](https://github.com/nodejs/node/pull/11708). * Convert `inspect.styles` and `inspect.colors` to prototype-less objects [[`aab0d202f8`](https://github.com/nodejs/node/commit/aab0d202f8)] [#11624](https://github.com/nodejs/node/pull/11624). * The new `util.promisify()` API has been added [[`99da8e8e02`](https://github.com/nodejs/node/commit/99da8e8e02)] [#12442](https://github.com/nodejs/node/pull/12442). * **Zlib** * Support `Uint8Array` in Zlib convenience methods [[`91383e47fd`](https://github.com/nodejs/node/commit/91383e47fd)] [#12001](https://github.com/nodejs/node/pull/12001). * Zlib errors now use `RangeError` and `TypeError` consistently [[`b514bd231e`](https://github.com/nodejs/node/commit/b514bd231e)] [#11391](https://github.com/nodejs/node/pull/11391).
2017-03-16 04:26:14 +01:00
- version: v8.0.0
pr-url: https://github.com/nodejs/node/pull/11608
description: The `chunk` argument can now be a `Uint8Array` instance.
-->
* `chunk` {Buffer|Uint8Array|string|null|any} Chunk of data to unshift onto the
read queue. For streams not operating in object mode, `chunk` must be a
string, `Buffer`, `Uint8Array` or `null`. For object mode streams, `chunk`
may be any JavaScript value.
* `encoding` {string} Encoding of string chunks. Must be a valid
`Buffer` encoding, such as `'utf8'` or `'ascii'`.
Passing `chunk` as `null` signals the end of the stream (EOF) and behaves the
same as `readable.push(null)`, after which no more data can be written. The EOF
signal is put at the end of the buffer and any buffered data will still be
flushed.
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.
The `stream.unshift(chunk)` method cannot be called after the [`'end'`][] event
has been emitted or a runtime error will be thrown.
Developers using `stream.unshift()` often should consider switching to
use of a [`Transform`][] stream instead. See the [API for stream implementers][]
section for more information.
```js
// Pull off a header delimited by \n\n.
// Use unshift() if we get too much.
// Call the callback with (error, header, stream).
const { StringDecoder } = require('string_decoder');
function parseHeader(stream, callback) {
stream.on('error', callback);
stream.on('readable', onReadable);
const decoder = new StringDecoder('utf8');
let header = '';
function onReadable() {
let chunk;
while (null !== (chunk = stream.read())) {
const str = decoder.write(chunk);
if (str.match(/\n\n/)) {
// Found the header boundary.
const split = str.split(/\n\n/);
header += split.shift();
const remaining = split.join('\n\n');
const buf = Buffer.from(remaining, 'utf8');
stream.removeListener('error', callback);
// Remove the 'readable' listener before unshifting.
stream.removeListener('readable', onReadable);
if (buf.length)
stream.unshift(buf);
// Now the body of the message can be read from the stream.
callback(null, header, stream);
} else {
// Still reading the header.
header += str;
}
}
}
}
```
Unlike [`stream.push(chunk)`][stream-push], `stream.unshift(chunk)` will not
end the reading process by resetting the internal reading state of the stream.
This can cause unexpected results if `readable.unshift()` is called during a
read (i.e. from within a [`stream._read()`][stream-_read] implementation on a
custom stream). Following the call to `readable.unshift()` with an immediate
[`stream.push('')`][stream-push] will reset the reading state appropriately,
however it is best to simply avoid calling `readable.unshift()` while in the
process of performing a read.
##### `readable.wrap(stream)`
<!-- YAML
added: v0.9.4
-->
* `stream` {Stream} An "old style" readable stream
* Returns: {this}
Prior to Node.js 0.10, streams did not implement the entire `stream` module API
as it is currently defined. (See [Compatibility][] for more information.)
When using an older Node.js library that emits [`'data'`][] events and has a
[`stream.pause()`][stream-pause] method that is advisory only, the
`readable.wrap()` method can be used to create a [`Readable`][] stream that uses
the old stream as its data source.
It will rarely be necessary to use `readable.wrap()` but the method has been
provided as a convenience for interacting with older Node.js applications and
libraries.
```js
const { OldReader } = require('./old-api-module.js');
const { Readable } = require('stream');
const oreader = new OldReader();
const myReader = new Readable().wrap(oreader);
myReader.on('readable', () => {
myReader.read(); // etc.
});
```
##### `readable[Symbol.asyncIterator]()`
<!-- YAML
2018-04-24, Version 10.0.0 (Current) * Assert * Calling `assert.fail()` with more than one argument is deprecated. #70dcacd710 * Calling `assert.ok()` with no arguments will now throw. #3cd7977a42 * Calling `assert.ifError()` will now throw with any argument other than `undefined` or `null`. Previously the method would throw with any truthy value. #e65a6e81ef * The `assert.rejects()` and `assert.doesNotReject()` methods have been added for working with async functions. #599337f43e * Async_hooks * Older experimental async_hooks APIs have been removed. #1cc6b993b9 * Buffer * Uses of `new Buffer()` and `Buffer()` outside of the `node_modules` directory will now emit a runtime deprecation warning. #9d4ab90117 * `Buffer.isEncoding()` now returns `undefined` for falsy values, including an empty string. #452eed956e * `Buffer.fill()` will throw if an attempt is made to fill with an empty `Buffer`. #1e802539b2 * Child Process * Undefined properties of env are ignored. #38ee25e2e2, #85739b6c5b * Console * The `console.table()` method has been added. #97ace04492 * Crypto * The `crypto.createCipher()` and `crypto.createDecipher()` methods have been deprecated. Please use `crypto.createCipheriv()` and `crypto.createDecipheriv()` instead. #81f88e30dd * The `decipher.finaltol()` method has been deprecated. #19f3927d92 * The `crypto.DEFAULT_ENCODING` property has been deprecated. #6035beea93 * The `ECDH.convertKey()` method has been added. #f2e02883e7 * The `crypto.fips` property has been deprecated. #6e7992e8b8 * Dependencies * V8 has been updated to 6.6. #9daebb48d6 * OpenSSL has been updated to 1.1.0h. #66cb29e646 * EventEmitter * The `EventEmitter.prototype.off()` method has been added as an alias for `EventEmitter.prototype.removeListener()`. #3bb6f07d52 * File System * The `fs.promises` API provides experimental promisified versions of the `fs` functions. #329fc78e49 * Invalid path errors are now thrown synchronously. #d8f73385e2 * The `fs.readFile()` method now partitions reads to avoid thread pool exhaustion. #67a4ce1c6e * HTTP * Processing of HTTP Status codes `100`, `102-199` has been improved. #baf8495078 * Multi-byte characters in URL paths are now forbidden. #b961d9fd83 * N-API * The n-api is no longer experimental. #cd7d7b15c1 * Net * The `'close'` event will be emitted after `'end'`. #9b7a6914a7 * Perf_hooks * The `PerformanceObserver` class is now an `AsyncResource` and can be monitored using `async_hooks`. #009e41826f * Trace events are now emitted for performance events. #9e509b622b * The `performance` API has been simplified. #2ec6995555 * Performance milestone marks will be emitted as trace events. #96cb4fb795 * Process * Using non-string values for `process.env` is deprecated. #5826fe4e79 * The `process.assert()` method is deprecated. #703e37cf3f * REPL * REPL now experimentally supports top-level await when using the `--experimental-repl-await` flag. #eeab7bc068 * The previously deprecated "magic mode" has been removed. #4893f70d12 * The previously deprecated `NODE_REPL_HISTORY_FILE` environment variable has been removed. #60c9ad7979 * Proxy objects are shown as Proxy objects when inspected. #90a43906ab * Streams * The `'readable'` event is now always deferred with nextTick. #1e0f3315c7 * A new `pipeline()` method has been provided for building end-to-data stream pipelines. #a5cf3feaf1 * Experimental support for async for-await has been added to `stream.Readable`. #61b4d60c5d * Timers * The `enroll()` and `unenroll()` methods have been deprecated. #68783ae0b8 * TLS * The `tls.convertNONProtocols()` method has been deprecated. #9204a0db6e * Support for NPN (next protocol negotiation) has been dropped. #5bfbe5ceae * The `ecdhCurve` default is now `'auto'`. #af78840b19 * Trace Events * A new `trace_events` top-level module allows trace event categories to be enabled/disabld at runtime. #da5d818a54 * URL * The WHATWG URL API is now a global. #312414662b * Util * `util.types.is[…]` type checks have been added. #b20af8088a * Support for bigint formatting has been added to `util.inspect()`. #39dc947409
2018-03-02 18:53:46 +01:00
added: v10.0.0
changes:
- version: v11.14.0
pr-url: https://github.com/nodejs/node/pull/26989
description: Symbol.asyncIterator support is no longer experimental.
-->
* Returns: {AsyncIterator} to fully consume the stream.
```js
const fs = require('fs');
async function print(readable) {
readable.setEncoding('utf8');
let data = '';
for await (const chunk of readable) {
data += chunk;
}
console.log(data);
}
print(fs.createReadStream('file')).catch(console.error);
```
If the loop terminates with a `break` or a `throw`, the stream will be
destroyed. In other terms, iterating over a stream will consume the stream
fully. The stream will be read in chunks of size equal to the `highWaterMark`
option. In the code example above, data will be in a single chunk if the file
has less then 64KB of data because no `highWaterMark` option is provided to
[`fs.createReadStream()`][].
### Duplex and transform streams
#### Class: `stream.Duplex`
<!-- YAML
added: v0.9.4
changes:
- version: v6.8.0
pr-url: https://github.com/nodejs/node/pull/8834
description: Instances of `Duplex` now return `true` when
checking `instanceof stream.Writable`.
-->
<!--type=class-->
Duplex streams are streams that implement both the [`Readable`][] and
[`Writable`][] interfaces.
Examples of `Duplex` streams include:
* [TCP sockets][]
* [zlib streams][zlib]
* [crypto streams][crypto]
#### Class: `stream.Transform`
<!-- YAML
added: v0.9.4
-->
<!--type=class-->
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.
Examples of `Transform` streams include:
* [zlib streams][zlib]
* [crypto streams][crypto]
##### `transform.destroy([error])`
<!-- YAML
2017-05-30, Version 8.0.0 (Current) * **Async Hooks** * The `async_hooks` module has landed in core [[`4a7233c178`](https://github.com/nodejs/node/commit/4a7233c178)] [#12892](https://github.com/nodejs/node/pull/12892). * **Buffer** * Using the `--pending-deprecation` flag will cause Node.js to emit a deprecation warning when using `new Buffer(num)` or `Buffer(num)`. [[`d2d32ea5a2`](https://github.com/nodejs/node/commit/d2d32ea5a2)] [#11968](https://github.com/nodejs/node/pull/11968). * `new Buffer(num)` and `Buffer(num)` will zero-fill new `Buffer` instances [[`7eb1b4658e`](https://github.com/nodejs/node/commit/7eb1b4658e)] [#12141](https://github.com/nodejs/node/pull/12141). * Many `Buffer` methods now accept `Uint8Array` as input [[`beca3244e2`](https://github.com/nodejs/node/commit/beca3244e2)] [#10236](https://github.com/nodejs/node/pull/10236). * **Child Process** * Argument and kill signal validations have been improved [[`97a77288ce`](https://github.com/nodejs/node/commit/97a77288ce)] [#12348](https://github.com/nodejs/node/pull/12348), [[`d75fdd96aa`](https://github.com/nodejs/node/commit/d75fdd96aa)] [#10423](https://github.com/nodejs/node/pull/10423). * Child Process methods accept `Uint8Array` as input [[`627ecee9ed`](https://github.com/nodejs/node/commit/627ecee9ed)] [#10653](https://github.com/nodejs/node/pull/10653). * **Console** * Error events emitted when using `console` methods are now supressed. [[`f18e08d820`](https://github.com/nodejs/node/commit/f18e08d820)] [#9744](https://github.com/nodejs/node/pull/9744). * **Dependencies** * The npm client has been updated to 5.0.0 [[`3c3b36af0f`](https://github.com/nodejs/node/commit/3c3b36af0f)] [#12936](https://github.com/nodejs/node/pull/12936). * V8 has been updated to 5.8 with forward ABI stability to 6.0 [[`60d1aac8d2`](https://github.com/nodejs/node/commit/60d1aac8d2)] [#12784](https://github.com/nodejs/node/pull/12784). * **Domains** * Native `Promise` instances are now `Domain` aware [[`84dabe8373`](https://github.com/nodejs/node/commit/84dabe8373)] [#12489](https://github.com/nodejs/node/pull/12489). * **Errors** * We have started assigning static error codes to errors generated by Node.js. This has been done through multiple commits and is still a work in progress. * **File System** * The utility class `fs.SyncWriteStream` has been deprecated [[`7a55e34ef4`](https://github.com/nodejs/node/commit/7a55e34ef4)] [#10467](https://github.com/nodejs/node/pull/10467). * The deprecated `fs.read()` string interface has been removed [[`3c2a9361ff`](https://github.com/nodejs/node/commit/3c2a9361ff)] [#9683](https://github.com/nodejs/node/pull/9683). * **HTTP** * Improved support for userland implemented Agents [[`90403dd1d0`](https://github.com/nodejs/node/commit/90403dd1d0)] [#11567](https://github.com/nodejs/node/pull/11567). * Outgoing Cookie headers are concatenated into a single string [[`d3480776c7`](https://github.com/nodejs/node/commit/d3480776c7)] [#11259](https://github.com/nodejs/node/pull/11259). * The `httpResponse.writeHeader()` method has been deprecated [[`fb71ba4921`](https://github.com/nodejs/node/commit/fb71ba4921)] [#11355](https://github.com/nodejs/node/pull/11355). * New methods for accessing HTTP headers have been added to `OutgoingMessage` [[`3e6f1032a4`](https://github.com/nodejs/node/commit/3e6f1032a4)] [#10805](https://github.com/nodejs/node/pull/10805). * **Lib** * All deprecation messages have been assigned static identifiers [[`5de3cf099c`](https://github.com/nodejs/node/commit/5de3cf099c)] [#10116](https://github.com/nodejs/node/pull/10116). * The legacy `linkedlist` module has been removed [[`84a23391f6`](https://github.com/nodejs/node/commit/84a23391f6)] [#12113](https://github.com/nodejs/node/pull/12113). * **N-API** * Experimental support for the new N-API API has been added [[`56e881d0b0`](https://github.com/nodejs/node/commit/56e881d0b0)] [#11975](https://github.com/nodejs/node/pull/11975). * **Process** * Process warning output can be redirected to a file using the `--redirect-warnings` command-line argument [[`03e89b3ff2`](https://github.com/nodejs/node/commit/03e89b3ff2)] [#10116](https://github.com/nodejs/node/pull/10116). * Process warnings may now include additional detail [[`dd20e68b0f`](https://github.com/nodejs/node/commit/dd20e68b0f)] [#12725](https://github.com/nodejs/node/pull/12725). * **REPL** * REPL magic mode has been deprecated [[`3f27f02da0`](https://github.com/nodejs/node/commit/3f27f02da0)] [#11599](https://github.com/nodejs/node/pull/11599). * **Src** * `NODE_MODULE_VERSION` has been updated to 57 (https://github.com/nodejs/node/commit/ec7cbaf266)] [#12995](https://github.com/nodejs/node/pull/12995). * Add `--pending-deprecation` command-line argument and `NODE_PENDING_DEPRECATION` environment variable [[`a16b570f8c`](https://github.com/nodejs/node/commit/a16b570f8c)] [#11968](https://github.com/nodejs/node/pull/11968). * The `--debug` command-line argument has been deprecated. Note that using `--debug` will enable the *new* Inspector-based debug protocol as the legacy Debugger protocol previously used by Node.js has been removed. [[`010f864426`](https://github.com/nodejs/node/commit/010f864426)] [#12949](https://github.com/nodejs/node/pull/12949). * Throw when the `-c` and `-e` command-line arguments are used at the same time [[`a5f91ab230`](https://github.com/nodejs/node/commit/a5f91ab230)] [#11689](https://github.com/nodejs/node/pull/11689). * Throw when the `--use-bundled-ca` and `--use-openssl-ca` command-line arguments are used at the same time. [[`8a7db9d4b5`](https://github.com/nodejs/node/commit/8a7db9d4b5)] [#12087](https://github.com/nodejs/node/pull/12087). * **Stream** * `Stream` now supports `destroy()` and `_destroy()` APIs [[`b6e1d22fa6`](https://github.com/nodejs/node/commit/b6e1d22fa6)] [#12925](https://github.com/nodejs/node/pull/12925). * `Stream` now supports the `_final()` API [[`07c7f198db`](https://github.com/nodejs/node/commit/07c7f198db)] [#12828](https://github.com/nodejs/node/pull/12828). * **TLS** * The `rejectUnauthorized` option now defaults to `true` [[`348cc80a3c`](https://github.com/nodejs/node/commit/348cc80a3c)] [#5923](https://github.com/nodejs/node/pull/5923). * The `tls.createSecurePair()` API now emits a runtime deprecation [[`a2ae08999b`](https://github.com/nodejs/node/commit/a2ae08999b)] [#11349](https://github.com/nodejs/node/pull/11349). * A runtime deprecation will now be emitted when `dhparam` is less than 2048 bits [[`d523eb9c40`](https://github.com/nodejs/node/commit/d523eb9c40)] [#11447](https://github.com/nodejs/node/pull/11447). * **URL** * The WHATWG URL implementation is now a fully-supported Node.js API [[`d080ead0f9`](https://github.com/nodejs/node/commit/d080ead0f9)] [#12710](https://github.com/nodejs/node/pull/12710). * **Util** * `Symbol` keys are now displayed by default when using `util.inspect()` [[`5bfd13b81e`](https://github.com/nodejs/node/commit/5bfd13b81e)] [#9726](https://github.com/nodejs/node/pull/9726). * `toJSON` errors will be thrown when formatting `%j` [[`455e6f1dd8`](https://github.com/nodejs/node/commit/455e6f1dd8)] [#11708](https://github.com/nodejs/node/pull/11708). * Convert `inspect.styles` and `inspect.colors` to prototype-less objects [[`aab0d202f8`](https://github.com/nodejs/node/commit/aab0d202f8)] [#11624](https://github.com/nodejs/node/pull/11624). * The new `util.promisify()` API has been added [[`99da8e8e02`](https://github.com/nodejs/node/commit/99da8e8e02)] [#12442](https://github.com/nodejs/node/pull/12442). * **Zlib** * Support `Uint8Array` in Zlib convenience methods [[`91383e47fd`](https://github.com/nodejs/node/commit/91383e47fd)] [#12001](https://github.com/nodejs/node/pull/12001). * Zlib errors now use `RangeError` and `TypeError` consistently [[`b514bd231e`](https://github.com/nodejs/node/commit/b514bd231e)] [#11391](https://github.com/nodejs/node/pull/11391).
2017-03-16 04:26:14 +01:00
added: v8.0.0
-->
* `error` {Error}
* Returns: {this}
Destroy the stream, and optionally emit an `'error'` event. After this call, the
transform stream would release any internal resources.
Implementors should not override this method, but instead implement
[`readable._destroy()`][readable-_destroy].
The default implementation of `_destroy()` for `Transform` also emit `'close'`
unless `emitClose` is set in false.
Once `destroy()` has been called any further calls will be a noop and no
further errors except from `_destroy` may be emitted as `'error'`.
### `stream.finished(stream[, options], callback)`
<!-- YAML
2018-04-24, Version 10.0.0 (Current) * Assert * Calling `assert.fail()` with more than one argument is deprecated. #70dcacd710 * Calling `assert.ok()` with no arguments will now throw. #3cd7977a42 * Calling `assert.ifError()` will now throw with any argument other than `undefined` or `null`. Previously the method would throw with any truthy value. #e65a6e81ef * The `assert.rejects()` and `assert.doesNotReject()` methods have been added for working with async functions. #599337f43e * Async_hooks * Older experimental async_hooks APIs have been removed. #1cc6b993b9 * Buffer * Uses of `new Buffer()` and `Buffer()` outside of the `node_modules` directory will now emit a runtime deprecation warning. #9d4ab90117 * `Buffer.isEncoding()` now returns `undefined` for falsy values, including an empty string. #452eed956e * `Buffer.fill()` will throw if an attempt is made to fill with an empty `Buffer`. #1e802539b2 * Child Process * Undefined properties of env are ignored. #38ee25e2e2, #85739b6c5b * Console * The `console.table()` method has been added. #97ace04492 * Crypto * The `crypto.createCipher()` and `crypto.createDecipher()` methods have been deprecated. Please use `crypto.createCipheriv()` and `crypto.createDecipheriv()` instead. #81f88e30dd * The `decipher.finaltol()` method has been deprecated. #19f3927d92 * The `crypto.DEFAULT_ENCODING` property has been deprecated. #6035beea93 * The `ECDH.convertKey()` method has been added. #f2e02883e7 * The `crypto.fips` property has been deprecated. #6e7992e8b8 * Dependencies * V8 has been updated to 6.6. #9daebb48d6 * OpenSSL has been updated to 1.1.0h. #66cb29e646 * EventEmitter * The `EventEmitter.prototype.off()` method has been added as an alias for `EventEmitter.prototype.removeListener()`. #3bb6f07d52 * File System * The `fs.promises` API provides experimental promisified versions of the `fs` functions. #329fc78e49 * Invalid path errors are now thrown synchronously. #d8f73385e2 * The `fs.readFile()` method now partitions reads to avoid thread pool exhaustion. #67a4ce1c6e * HTTP * Processing of HTTP Status codes `100`, `102-199` has been improved. #baf8495078 * Multi-byte characters in URL paths are now forbidden. #b961d9fd83 * N-API * The n-api is no longer experimental. #cd7d7b15c1 * Net * The `'close'` event will be emitted after `'end'`. #9b7a6914a7 * Perf_hooks * The `PerformanceObserver` class is now an `AsyncResource` and can be monitored using `async_hooks`. #009e41826f * Trace events are now emitted for performance events. #9e509b622b * The `performance` API has been simplified. #2ec6995555 * Performance milestone marks will be emitted as trace events. #96cb4fb795 * Process * Using non-string values for `process.env` is deprecated. #5826fe4e79 * The `process.assert()` method is deprecated. #703e37cf3f * REPL * REPL now experimentally supports top-level await when using the `--experimental-repl-await` flag. #eeab7bc068 * The previously deprecated "magic mode" has been removed. #4893f70d12 * The previously deprecated `NODE_REPL_HISTORY_FILE` environment variable has been removed. #60c9ad7979 * Proxy objects are shown as Proxy objects when inspected. #90a43906ab * Streams * The `'readable'` event is now always deferred with nextTick. #1e0f3315c7 * A new `pipeline()` method has been provided for building end-to-data stream pipelines. #a5cf3feaf1 * Experimental support for async for-await has been added to `stream.Readable`. #61b4d60c5d * Timers * The `enroll()` and `unenroll()` methods have been deprecated. #68783ae0b8 * TLS * The `tls.convertNONProtocols()` method has been deprecated. #9204a0db6e * Support for NPN (next protocol negotiation) has been dropped. #5bfbe5ceae * The `ecdhCurve` default is now `'auto'`. #af78840b19 * Trace Events * A new `trace_events` top-level module allows trace event categories to be enabled/disabld at runtime. #da5d818a54 * URL * The WHATWG URL API is now a global. #312414662b * Util * `util.types.is[…]` type checks have been added. #b20af8088a * Support for bigint formatting has been added to `util.inspect()`. #39dc947409
2018-03-02 18:53:46 +01:00
added: v10.0.0
changes:
- version: v14.0.0
pr-url: https://github.com/nodejs/node/pull/32158
description: The `finished(stream, cb)` will wait for the `'close'` event
before invoking the callback. The implementation tries to
detect legacy streams and only apply this behavior to streams
which are expected to emit `'close'`.
- version: v14.0.0
pr-url: https://github.com/nodejs/node/pull/31545
description: Emitting `'close'` before `'end'` on a `Readable` stream
will cause an `ERR_STREAM_PREMATURE_CLOSE` error.
- version: v14.0.0
pr-url: https://github.com/nodejs/node/pull/31509
description: Callback will be invoked on streams which have already
finished before the call to `finished(stream, cb)`.
-->
* `stream` {Stream} A readable and/or writable stream.
* `options` {Object}
* `error` {boolean} If set to `false`, then a call to `emit('error', err)` is
not treated as finished. **Default**: `true`.
* `readable` {boolean} When set to `false`, the callback will be called when
the stream ends even though the stream might still be readable.
**Default**: `true`.
* `writable` {boolean} When set to `false`, the callback will be called when
the stream ends even though the stream might still be writable.
**Default**: `true`.
* `callback` {Function} A callback function that takes an optional error
argument.
* Returns: {Function} A cleanup function which removes all registered
listeners.
A function to get notified when a stream is no longer readable, writable
or has experienced an error or a premature close event.
```js
const { finished } = require('stream');
const rs = fs.createReadStream('archive.tar');
finished(rs, (err) => {
if (err) {
console.error('Stream failed.', err);
} else {
console.log('Stream is done reading.');
}
});
rs.resume(); // Drain the stream.
```
Especially useful in error handling scenarios where a stream is destroyed
prematurely (like an aborted HTTP request), and will not emit `'end'`
or `'finish'`.
The `finished` API is promisify-able as well;
```js
const finished = util.promisify(stream.finished);
const rs = fs.createReadStream('archive.tar');
async function run() {
await finished(rs);
console.log('Stream is done reading.');
}
run().catch(console.error);
rs.resume(); // Drain the stream.
```
`stream.finished()` leaves dangling event listeners (in particular
`'error'`, `'end'`, `'finish'` and `'close'`) after `callback` has been
invoked. The reason for this is so that unexpected `'error'` events (due to
incorrect stream implementations) do not cause unexpected crashes.
If this is unwanted behavior then the returned cleanup function needs to be
invoked in the callback:
```js
const cleanup = finished(rs, (err) => {
cleanup();
// ...
});
```
### `stream.pipeline(source[, ...transforms], destination, callback)`
<!-- YAML
2018-04-24, Version 10.0.0 (Current) * Assert * Calling `assert.fail()` with more than one argument is deprecated. #70dcacd710 * Calling `assert.ok()` with no arguments will now throw. #3cd7977a42 * Calling `assert.ifError()` will now throw with any argument other than `undefined` or `null`. Previously the method would throw with any truthy value. #e65a6e81ef * The `assert.rejects()` and `assert.doesNotReject()` methods have been added for working with async functions. #599337f43e * Async_hooks * Older experimental async_hooks APIs have been removed. #1cc6b993b9 * Buffer * Uses of `new Buffer()` and `Buffer()` outside of the `node_modules` directory will now emit a runtime deprecation warning. #9d4ab90117 * `Buffer.isEncoding()` now returns `undefined` for falsy values, including an empty string. #452eed956e * `Buffer.fill()` will throw if an attempt is made to fill with an empty `Buffer`. #1e802539b2 * Child Process * Undefined properties of env are ignored. #38ee25e2e2, #85739b6c5b * Console * The `console.table()` method has been added. #97ace04492 * Crypto * The `crypto.createCipher()` and `crypto.createDecipher()` methods have been deprecated. Please use `crypto.createCipheriv()` and `crypto.createDecipheriv()` instead. #81f88e30dd * The `decipher.finaltol()` method has been deprecated. #19f3927d92 * The `crypto.DEFAULT_ENCODING` property has been deprecated. #6035beea93 * The `ECDH.convertKey()` method has been added. #f2e02883e7 * The `crypto.fips` property has been deprecated. #6e7992e8b8 * Dependencies * V8 has been updated to 6.6. #9daebb48d6 * OpenSSL has been updated to 1.1.0h. #66cb29e646 * EventEmitter * The `EventEmitter.prototype.off()` method has been added as an alias for `EventEmitter.prototype.removeListener()`. #3bb6f07d52 * File System * The `fs.promises` API provides experimental promisified versions of the `fs` functions. #329fc78e49 * Invalid path errors are now thrown synchronously. #d8f73385e2 * The `fs.readFile()` method now partitions reads to avoid thread pool exhaustion. #67a4ce1c6e * HTTP * Processing of HTTP Status codes `100`, `102-199` has been improved. #baf8495078 * Multi-byte characters in URL paths are now forbidden. #b961d9fd83 * N-API * The n-api is no longer experimental. #cd7d7b15c1 * Net * The `'close'` event will be emitted after `'end'`. #9b7a6914a7 * Perf_hooks * The `PerformanceObserver` class is now an `AsyncResource` and can be monitored using `async_hooks`. #009e41826f * Trace events are now emitted for performance events. #9e509b622b * The `performance` API has been simplified. #2ec6995555 * Performance milestone marks will be emitted as trace events. #96cb4fb795 * Process * Using non-string values for `process.env` is deprecated. #5826fe4e79 * The `process.assert()` method is deprecated. #703e37cf3f * REPL * REPL now experimentally supports top-level await when using the `--experimental-repl-await` flag. #eeab7bc068 * The previously deprecated "magic mode" has been removed. #4893f70d12 * The previously deprecated `NODE_REPL_HISTORY_FILE` environment variable has been removed. #60c9ad7979 * Proxy objects are shown as Proxy objects when inspected. #90a43906ab * Streams * The `'readable'` event is now always deferred with nextTick. #1e0f3315c7 * A new `pipeline()` method has been provided for building end-to-data stream pipelines. #a5cf3feaf1 * Experimental support for async for-await has been added to `stream.Readable`. #61b4d60c5d * Timers * The `enroll()` and `unenroll()` methods have been deprecated. #68783ae0b8 * TLS * The `tls.convertNONProtocols()` method has been deprecated. #9204a0db6e * Support for NPN (next protocol negotiation) has been dropped. #5bfbe5ceae * The `ecdhCurve` default is now `'auto'`. #af78840b19 * Trace Events * A new `trace_events` top-level module allows trace event categories to be enabled/disabld at runtime. #da5d818a54 * URL * The WHATWG URL API is now a global. #312414662b * Util * `util.types.is[…]` type checks have been added. #b20af8088a * Support for bigint formatting has been added to `util.inspect()`. #39dc947409
2018-03-02 18:53:46 +01:00
added: v10.0.0
changes:
- version: v13.10.0
pr-url: https://github.com/nodejs/node/pull/31223
description: Add support for async generators.
- version: v14.0.0
pr-url: https://github.com/nodejs/node/pull/32158
description: The `pipeline(..., cb)` will wait for the `'close'` event
before invoking the callback. The implementation tries to
detect legacy streams and only apply this behavior to streams
which are expected to emit `'close'`.
-->
* `source` {Stream|Iterable|AsyncIterable|Function}
* Returns: {Iterable|AsyncIterable}
* `...transforms` {Stream|Function}
* `source` {AsyncIterable}
* Returns: {AsyncIterable}
* `destination` {Stream|Function}
* `source` {AsyncIterable}
* Returns: {AsyncIterable|Promise}
* `callback` {Function} Called when the pipeline is fully done.
* `err` {Error}
* `val` Resolved value of `Promise` returned by `destination`.
* Returns: {Stream}
A module method to pipe between streams and generators forwarding errors and
properly cleaning up and provide a callback when the pipeline is complete.
```js
const { pipeline } = require('stream');
const fs = require('fs');
const zlib = require('zlib');
// Use the pipeline API to easily pipe a series of streams
// together and get notified when the pipeline is fully done.
// A pipeline to gzip a potentially huge tar file efficiently:
pipeline(
fs.createReadStream('archive.tar'),
zlib.createGzip(),
fs.createWriteStream('archive.tar.gz'),
(err) => {
if (err) {
console.error('Pipeline failed.', err);
} else {
console.log('Pipeline succeeded.');
}
}
);
```
The `pipeline` API is promisify-able as well:
```js
const pipeline = util.promisify(stream.pipeline);
async function run() {
await pipeline(
fs.createReadStream('archive.tar'),
zlib.createGzip(),
fs.createWriteStream('archive.tar.gz')
);
console.log('Pipeline succeeded.');
}
run().catch(console.error);
```
The `pipeline` API also supports async generators:
```js
const pipeline = util.promisify(stream.pipeline);
const fs = require('fs');
async function run() {
await pipeline(
fs.createReadStream('lowercase.txt'),
async function* (source) {
source.setEncoding('utf8'); // Work with strings rather than `Buffer`s.
for await (const chunk of source) {
yield chunk.toUpperCase();
}
},
fs.createWriteStream('uppercase.txt')
);
console.log('Pipeline succeeded.');
}
run().catch(console.error);
```
`stream.pipeline()` will call `stream.destroy(err)` on all streams except:
* `Readable` streams which have emitted `'end'` or `'close'`.
* `Writable` streams which have emitted `'finish'` or `'close'`.
`stream.pipeline()` leaves dangling event listeners on the streams
after the `callback` has been invoked. In the case of reuse of streams after
failure, this can cause event listener leaks and swallowed errors.
### `stream.Readable.from(iterable, [options])`
<!-- YAML
added:
- v12.3.0
- v10.17.0
-->
* `iterable` {Iterable} Object implementing the `Symbol.asyncIterator` or
`Symbol.iterator` iterable protocol. Emits an 'error' event if a null
value is passed.
* `options` {Object} Options provided to `new stream.Readable([options])`.
By default, `Readable.from()` will set `options.objectMode` to `true`, unless
this is explicitly opted out by setting `options.objectMode` to `false`.
* Returns: {stream.Readable}
A utility method for creating readable streams out of iterators.
```js
const { Readable } = require('stream');
async function * generate() {
yield 'hello';
yield 'streams';
}
const readable = Readable.from(generate());
readable.on('data', (chunk) => {
console.log(chunk);
});
```
Calling `Readable.from(string)` or `Readable.from(buffer)` will not have
the strings or buffers be iterated to match the other streams semantics
for performance reasons.
## API for stream implementers
<!--type=misc-->
The `stream` module API has been designed to make it possible to easily
implement streams using JavaScript's prototypal inheritance model.
First, a stream developer would declare a new JavaScript class that extends one
of the four basic stream classes (`stream.Writable`, `stream.Readable`,
`stream.Duplex`, or `stream.Transform`), making sure they call the appropriate
parent class constructor:
<!-- eslint-disable no-useless-constructor -->
```js
const { Writable } = require('stream');
class MyWritable extends Writable {
constructor({ highWaterMark, ...options }) {
super({ highWaterMark });
// ...
}
}
```
When extending streams, keep in mind what options the user
can and should provide before forwarding these to the base constructor. For
example, if the implementation makes assumptions in regard to the
`autoDestroy` and `emitClose` options, do not allow the
user to override these. Be explicit about what
options are forwarded instead of implicitly forwarding all options.
The new stream class must then implement one or more specific methods, depending
on the type of stream being created, as detailed in the chart below:
| Use-case | Class | Method(s) to implement |
| -------- | ----- | ---------------------- |
| Reading only | [`Readable`][] | [`_read()`][stream-_read] |
| Writing only | [`Writable`][] | [`_write()`][stream-_write], [`_writev()`][stream-_writev], [`_final()`][stream-_final] |
| Reading and writing | [`Duplex`][] | [`_read()`][stream-_read], [`_write()`][stream-_write], [`_writev()`][stream-_writev], [`_final()`][stream-_final] |
| Operate on written data, then read the result | [`Transform`][] | [`_transform()`][stream-_transform], [`_flush()`][stream-_flush], [`_final()`][stream-_final] |
The implementation code for a stream should *never* call the "public" methods
of a stream that are intended for use by consumers (as described in the
[API for stream consumers][] section). Doing so may lead to adverse side effects
in application code consuming the stream.
Avoid overriding public methods such as `write()`, `end()`, `cork()`,
`uncork()`, `read()` and `destroy()`, or emitting internal events such
as `'error'`, `'data'`, `'end'`, `'finish'` and `'close'` through `.emit()`.
Doing so can break current and future stream invariants leading to behavior
and/or compatibility issues with other streams, stream utilities, and user
expectations.
### Simplified construction
<!-- YAML
added: v1.2.0
-->
For many simple cases, it is possible to create a stream without relying on
inheritance. This can be accomplished by directly creating instances of the
`stream.Writable`, `stream.Readable`, `stream.Duplex` or `stream.Transform`
objects and passing appropriate methods as constructor options.
```js
const { Writable } = require('stream');
const myWritable = new Writable({
construct(callback) {
// Initialize state and load resources...
},
write(chunk, encoding, callback) {
// ...
},
destroy() {
// Free resources...
}
});
```
### Implementing a writable stream
The `stream.Writable` class is extended to implement a [`Writable`][] stream.
Custom `Writable` streams *must* call the `new stream.Writable([options])`
constructor and implement the `writable._write()` and/or `writable._writev()`
method.
#### `new stream.Writable([options])`
<!-- YAML
changes:
- version: v14.0.0
pr-url: https://github.com/nodejs/node/pull/30623
description: Change `autoDestroy` option default to `true`.
- version:
- v11.2.0
- v10.16.0
pr-url: https://github.com/nodejs/node/pull/22795
description: Add `autoDestroy` option to automatically `destroy()` the
stream when it emits `'finish'` or errors.
2018-04-24, Version 10.0.0 (Current) * Assert * Calling `assert.fail()` with more than one argument is deprecated. #70dcacd710 * Calling `assert.ok()` with no arguments will now throw. #3cd7977a42 * Calling `assert.ifError()` will now throw with any argument other than `undefined` or `null`. Previously the method would throw with any truthy value. #e65a6e81ef * The `assert.rejects()` and `assert.doesNotReject()` methods have been added for working with async functions. #599337f43e * Async_hooks * Older experimental async_hooks APIs have been removed. #1cc6b993b9 * Buffer * Uses of `new Buffer()` and `Buffer()` outside of the `node_modules` directory will now emit a runtime deprecation warning. #9d4ab90117 * `Buffer.isEncoding()` now returns `undefined` for falsy values, including an empty string. #452eed956e * `Buffer.fill()` will throw if an attempt is made to fill with an empty `Buffer`. #1e802539b2 * Child Process * Undefined properties of env are ignored. #38ee25e2e2, #85739b6c5b * Console * The `console.table()` method has been added. #97ace04492 * Crypto * The `crypto.createCipher()` and `crypto.createDecipher()` methods have been deprecated. Please use `crypto.createCipheriv()` and `crypto.createDecipheriv()` instead. #81f88e30dd * The `decipher.finaltol()` method has been deprecated. #19f3927d92 * The `crypto.DEFAULT_ENCODING` property has been deprecated. #6035beea93 * The `ECDH.convertKey()` method has been added. #f2e02883e7 * The `crypto.fips` property has been deprecated. #6e7992e8b8 * Dependencies * V8 has been updated to 6.6. #9daebb48d6 * OpenSSL has been updated to 1.1.0h. #66cb29e646 * EventEmitter * The `EventEmitter.prototype.off()` method has been added as an alias for `EventEmitter.prototype.removeListener()`. #3bb6f07d52 * File System * The `fs.promises` API provides experimental promisified versions of the `fs` functions. #329fc78e49 * Invalid path errors are now thrown synchronously. #d8f73385e2 * The `fs.readFile()` method now partitions reads to avoid thread pool exhaustion. #67a4ce1c6e * HTTP * Processing of HTTP Status codes `100`, `102-199` has been improved. #baf8495078 * Multi-byte characters in URL paths are now forbidden. #b961d9fd83 * N-API * The n-api is no longer experimental. #cd7d7b15c1 * Net * The `'close'` event will be emitted after `'end'`. #9b7a6914a7 * Perf_hooks * The `PerformanceObserver` class is now an `AsyncResource` and can be monitored using `async_hooks`. #009e41826f * Trace events are now emitted for performance events. #9e509b622b * The `performance` API has been simplified. #2ec6995555 * Performance milestone marks will be emitted as trace events. #96cb4fb795 * Process * Using non-string values for `process.env` is deprecated. #5826fe4e79 * The `process.assert()` method is deprecated. #703e37cf3f * REPL * REPL now experimentally supports top-level await when using the `--experimental-repl-await` flag. #eeab7bc068 * The previously deprecated "magic mode" has been removed. #4893f70d12 * The previously deprecated `NODE_REPL_HISTORY_FILE` environment variable has been removed. #60c9ad7979 * Proxy objects are shown as Proxy objects when inspected. #90a43906ab * Streams * The `'readable'` event is now always deferred with nextTick. #1e0f3315c7 * A new `pipeline()` method has been provided for building end-to-data stream pipelines. #a5cf3feaf1 * Experimental support for async for-await has been added to `stream.Readable`. #61b4d60c5d * Timers * The `enroll()` and `unenroll()` methods have been deprecated. #68783ae0b8 * TLS * The `tls.convertNONProtocols()` method has been deprecated. #9204a0db6e * Support for NPN (next protocol negotiation) has been dropped. #5bfbe5ceae * The `ecdhCurve` default is now `'auto'`. #af78840b19 * Trace Events * A new `trace_events` top-level module allows trace event categories to be enabled/disabld at runtime. #da5d818a54 * URL * The WHATWG URL API is now a global. #312414662b * Util * `util.types.is[…]` type checks have been added. #b20af8088a * Support for bigint formatting has been added to `util.inspect()`. #39dc947409
2018-03-02 18:53:46 +01:00
- version: v10.0.0
pr-url: https://github.com/nodejs/node/pull/18438
description: Add `emitClose` option to specify if `'close'` is emitted on
destroy.
-->
* `options` {Object}
* `highWaterMark` {number} Buffer level when
[`stream.write()`][stream-write] starts returning `false`. **Default:**
`16384` (16KB), or `16` for `objectMode` streams.
* `decodeStrings` {boolean} Whether to encode `string`s passed to
[`stream.write()`][stream-write] to `Buffer`s (with the encoding
specified in the [`stream.write()`][stream-write] call) before passing
them to [`stream._write()`][stream-_write]. Other types of data are not
converted (i.e. `Buffer`s are not decoded into `string`s). Setting to
false will prevent `string`s from being converted. **Default:** `true`.
* `defaultEncoding` {string} The default encoding that is used when no
encoding is specified as an argument to [`stream.write()`][stream-write].
**Default:** `'utf8'`.
* `objectMode` {boolean} Whether or not the
[`stream.write(anyObj)`][stream-write] is a valid operation. When set,
it becomes possible to write JavaScript values other than string,
`Buffer` or `Uint8Array` if supported by the stream implementation.
**Default:** `false`.
* `emitClose` {boolean} Whether or not the stream should emit `'close'`
after it has been destroyed. **Default:** `true`.
* `write` {Function} Implementation for the
[`stream._write()`][stream-_write] method.
* `writev` {Function} Implementation for the
[`stream._writev()`][stream-_writev] method.
* `destroy` {Function} Implementation for the
[`stream._destroy()`][writable-_destroy] method.
* `final` {Function} Implementation for the
[`stream._final()`][stream-_final] method.
* `construct` {Function} Implementation for the
[`stream._construct()`][writable-_construct] method.
* `autoDestroy` {boolean} Whether this stream should automatically call
`.destroy()` on itself after ending. **Default:** `true`.
<!-- eslint-disable no-useless-constructor -->
```js
const { Writable } = require('stream');
class MyWritable extends Writable {
constructor(options) {
// Calls the stream.Writable() constructor.
super(options);
// ...
}
}
```
Or, when using pre-ES6 style constructors:
```js
const { Writable } = require('stream');
const util = require('util');
function MyWritable(options) {
if (!(this instanceof MyWritable))
return new MyWritable(options);
Writable.call(this, options);
}
util.inherits(MyWritable, Writable);
```
Or, using the simplified constructor approach:
```js
const { Writable } = require('stream');
const myWritable = new Writable({
write(chunk, encoding, callback) {
// ...
},
writev(chunks, callback) {
// ...
}
});
```
#### `writable._construct(callback)`
<!-- YAML
added: REPLACEME
-->
* `callback` {Function} Call this function (optionally with an error
argument) when the stream has finished initializing.
The `_construct()` method MUST NOT be called directly. It may be implemented
by child classes, and if so, will be called by the internal `Writable`
class methods only.
This optional function will be called in a tick after the stream constructor
has returned, delaying any `_write`, `_final` and `_destroy` calls until
`callback` is called. This is useful to initialize state or asynchronously
initialize resources before the stream can be used.
```js
const { Writable } = require('stream');
const fs = require('fs');
class WriteStream extends Writable {
constructor(filename) {
super();
this.filename = filename;
this.fd = fd;
}
_construct(callback) {
fs.open(this.filename, (fd, err) => {
if (err) {
callback(err);
} else {
this.fd = fd;
callback();
}
});
}
_write(chunk, encoding, callback) {
fs.write(this.fd, chunk, callback);
}
_destroy(err, callback) {
if (this.fd) {
fs.close(this.fd, (er) => callback(er || err));
} else {
callback(err);
}
}
}
```
#### `writable._write(chunk, encoding, callback)`
<!-- YAML
changes:
- version: v12.11.0
pr-url: https://github.com/nodejs/node/pull/29639
description: _write() is optional when providing _writev().
-->
* `chunk` {Buffer|string|any} The `Buffer` to be written, converted from the
`string` passed to [`stream.write()`][stream-write]. If the stream's
`decodeStrings` option is `false` or the stream is operating in object mode,
the chunk will not be converted & will be whatever was passed to
[`stream.write()`][stream-write].
* `encoding` {string} If the chunk is a string, then `encoding` is the
character encoding of that string. If chunk is a `Buffer`, or if the
stream is operating in object mode, `encoding` may be ignored.
* `callback` {Function} Call this function (optionally with an error
argument) when processing is complete for the supplied chunk.
All `Writable` stream implementations must provide a
[`writable._write()`][stream-_write] and/or
[`writable._writev()`][stream-_writev] method to send data to the underlying
resource.
[`Transform`][] streams provide their own implementation of the
[`writable._write()`][stream-_write].
This function MUST NOT be called by application code directly. It should be
implemented by child classes, and called by the internal `Writable` class
methods only.
The `callback` function must be called synchronously inside of
`writable._write()` or asynchronously (i.e. different tick) to signal either
that the write completed successfully or failed with an error.
The first argument passed to the `callback` must be the `Error` object if the
call failed or `null` if the write succeeded.
All calls to `writable.write()` that occur between the time `writable._write()`
is called and the `callback` is called will cause the written data to be
buffered. When the `callback` is invoked, the stream might emit a [`'drain'`][]
event. If a stream implementation is capable of processing multiple chunks of
data at once, the `writable._writev()` method should be implemented.
If the `decodeStrings` property is explicitly set to `false` in the constructor
options, then `chunk` will remain the same object that is passed to `.write()`,
and may be a string rather than a `Buffer`. This is to support implementations
that have an optimized handling for certain string data encodings. In that case,
the `encoding` argument will indicate the character encoding of the string.
Otherwise, the `encoding` argument can be safely ignored.
The `writable._write()` method is prefixed with an underscore because it is
internal to the class that defines it, and should never be called directly by
user programs.
#### `writable._writev(chunks, callback)`
* `chunks` {Object[]} The chunks to be written. Each chunk has following
format: `{ chunk: ..., encoding: ... }`.
* `callback` {Function} A callback function (optionally with an error
argument) to be invoked when processing is complete for the supplied chunks.
This function MUST NOT be called by application code directly. It should be
implemented by child classes, and called by the internal `Writable` class
methods only.
The `writable._writev()` method may be implemented in addition or alternatively
to `writable._write()` in stream implementations that are capable of processing
multiple chunks of data at once. If implemented and if there is buffered data
from previous writes, `_writev()` will be called instead of `_write()`.
The `writable._writev()` method is prefixed with an underscore because it is
internal to the class that defines it, and should never be called directly by
user programs.
#### `writable._destroy(err, callback)`
<!-- YAML
2017-05-30, Version 8.0.0 (Current) * **Async Hooks** * The `async_hooks` module has landed in core [[`4a7233c178`](https://github.com/nodejs/node/commit/4a7233c178)] [#12892](https://github.com/nodejs/node/pull/12892). * **Buffer** * Using the `--pending-deprecation` flag will cause Node.js to emit a deprecation warning when using `new Buffer(num)` or `Buffer(num)`. [[`d2d32ea5a2`](https://github.com/nodejs/node/commit/d2d32ea5a2)] [#11968](https://github.com/nodejs/node/pull/11968). * `new Buffer(num)` and `Buffer(num)` will zero-fill new `Buffer` instances [[`7eb1b4658e`](https://github.com/nodejs/node/commit/7eb1b4658e)] [#12141](https://github.com/nodejs/node/pull/12141). * Many `Buffer` methods now accept `Uint8Array` as input [[`beca3244e2`](https://github.com/nodejs/node/commit/beca3244e2)] [#10236](https://github.com/nodejs/node/pull/10236). * **Child Process** * Argument and kill signal validations have been improved [[`97a77288ce`](https://github.com/nodejs/node/commit/97a77288ce)] [#12348](https://github.com/nodejs/node/pull/12348), [[`d75fdd96aa`](https://github.com/nodejs/node/commit/d75fdd96aa)] [#10423](https://github.com/nodejs/node/pull/10423). * Child Process methods accept `Uint8Array` as input [[`627ecee9ed`](https://github.com/nodejs/node/commit/627ecee9ed)] [#10653](https://github.com/nodejs/node/pull/10653). * **Console** * Error events emitted when using `console` methods are now supressed. [[`f18e08d820`](https://github.com/nodejs/node/commit/f18e08d820)] [#9744](https://github.com/nodejs/node/pull/9744). * **Dependencies** * The npm client has been updated to 5.0.0 [[`3c3b36af0f`](https://github.com/nodejs/node/commit/3c3b36af0f)] [#12936](https://github.com/nodejs/node/pull/12936). * V8 has been updated to 5.8 with forward ABI stability to 6.0 [[`60d1aac8d2`](https://github.com/nodejs/node/commit/60d1aac8d2)] [#12784](https://github.com/nodejs/node/pull/12784). * **Domains** * Native `Promise` instances are now `Domain` aware [[`84dabe8373`](https://github.com/nodejs/node/commit/84dabe8373)] [#12489](https://github.com/nodejs/node/pull/12489). * **Errors** * We have started assigning static error codes to errors generated by Node.js. This has been done through multiple commits and is still a work in progress. * **File System** * The utility class `fs.SyncWriteStream` has been deprecated [[`7a55e34ef4`](https://github.com/nodejs/node/commit/7a55e34ef4)] [#10467](https://github.com/nodejs/node/pull/10467). * The deprecated `fs.read()` string interface has been removed [[`3c2a9361ff`](https://github.com/nodejs/node/commit/3c2a9361ff)] [#9683](https://github.com/nodejs/node/pull/9683). * **HTTP** * Improved support for userland implemented Agents [[`90403dd1d0`](https://github.com/nodejs/node/commit/90403dd1d0)] [#11567](https://github.com/nodejs/node/pull/11567). * Outgoing Cookie headers are concatenated into a single string [[`d3480776c7`](https://github.com/nodejs/node/commit/d3480776c7)] [#11259](https://github.com/nodejs/node/pull/11259). * The `httpResponse.writeHeader()` method has been deprecated [[`fb71ba4921`](https://github.com/nodejs/node/commit/fb71ba4921)] [#11355](https://github.com/nodejs/node/pull/11355). * New methods for accessing HTTP headers have been added to `OutgoingMessage` [[`3e6f1032a4`](https://github.com/nodejs/node/commit/3e6f1032a4)] [#10805](https://github.com/nodejs/node/pull/10805). * **Lib** * All deprecation messages have been assigned static identifiers [[`5de3cf099c`](https://github.com/nodejs/node/commit/5de3cf099c)] [#10116](https://github.com/nodejs/node/pull/10116). * The legacy `linkedlist` module has been removed [[`84a23391f6`](https://github.com/nodejs/node/commit/84a23391f6)] [#12113](https://github.com/nodejs/node/pull/12113). * **N-API** * Experimental support for the new N-API API has been added [[`56e881d0b0`](https://github.com/nodejs/node/commit/56e881d0b0)] [#11975](https://github.com/nodejs/node/pull/11975). * **Process** * Process warning output can be redirected to a file using the `--redirect-warnings` command-line argument [[`03e89b3ff2`](https://github.com/nodejs/node/commit/03e89b3ff2)] [#10116](https://github.com/nodejs/node/pull/10116). * Process warnings may now include additional detail [[`dd20e68b0f`](https://github.com/nodejs/node/commit/dd20e68b0f)] [#12725](https://github.com/nodejs/node/pull/12725). * **REPL** * REPL magic mode has been deprecated [[`3f27f02da0`](https://github.com/nodejs/node/commit/3f27f02da0)] [#11599](https://github.com/nodejs/node/pull/11599). * **Src** * `NODE_MODULE_VERSION` has been updated to 57 (https://github.com/nodejs/node/commit/ec7cbaf266)] [#12995](https://github.com/nodejs/node/pull/12995). * Add `--pending-deprecation` command-line argument and `NODE_PENDING_DEPRECATION` environment variable [[`a16b570f8c`](https://github.com/nodejs/node/commit/a16b570f8c)] [#11968](https://github.com/nodejs/node/pull/11968). * The `--debug` command-line argument has been deprecated. Note that using `--debug` will enable the *new* Inspector-based debug protocol as the legacy Debugger protocol previously used by Node.js has been removed. [[`010f864426`](https://github.com/nodejs/node/commit/010f864426)] [#12949](https://github.com/nodejs/node/pull/12949). * Throw when the `-c` and `-e` command-line arguments are used at the same time [[`a5f91ab230`](https://github.com/nodejs/node/commit/a5f91ab230)] [#11689](https://github.com/nodejs/node/pull/11689). * Throw when the `--use-bundled-ca` and `--use-openssl-ca` command-line arguments are used at the same time. [[`8a7db9d4b5`](https://github.com/nodejs/node/commit/8a7db9d4b5)] [#12087](https://github.com/nodejs/node/pull/12087). * **Stream** * `Stream` now supports `destroy()` and `_destroy()` APIs [[`b6e1d22fa6`](https://github.com/nodejs/node/commit/b6e1d22fa6)] [#12925](https://github.com/nodejs/node/pull/12925). * `Stream` now supports the `_final()` API [[`07c7f198db`](https://github.com/nodejs/node/commit/07c7f198db)] [#12828](https://github.com/nodejs/node/pull/12828). * **TLS** * The `rejectUnauthorized` option now defaults to `true` [[`348cc80a3c`](https://github.com/nodejs/node/commit/348cc80a3c)] [#5923](https://github.com/nodejs/node/pull/5923). * The `tls.createSecurePair()` API now emits a runtime deprecation [[`a2ae08999b`](https://github.com/nodejs/node/commit/a2ae08999b)] [#11349](https://github.com/nodejs/node/pull/11349). * A runtime deprecation will now be emitted when `dhparam` is less than 2048 bits [[`d523eb9c40`](https://github.com/nodejs/node/commit/d523eb9c40)] [#11447](https://github.com/nodejs/node/pull/11447). * **URL** * The WHATWG URL implementation is now a fully-supported Node.js API [[`d080ead0f9`](https://github.com/nodejs/node/commit/d080ead0f9)] [#12710](https://github.com/nodejs/node/pull/12710). * **Util** * `Symbol` keys are now displayed by default when using `util.inspect()` [[`5bfd13b81e`](https://github.com/nodejs/node/commit/5bfd13b81e)] [#9726](https://github.com/nodejs/node/pull/9726). * `toJSON` errors will be thrown when formatting `%j` [[`455e6f1dd8`](https://github.com/nodejs/node/commit/455e6f1dd8)] [#11708](https://github.com/nodejs/node/pull/11708). * Convert `inspect.styles` and `inspect.colors` to prototype-less objects [[`aab0d202f8`](https://github.com/nodejs/node/commit/aab0d202f8)] [#11624](https://github.com/nodejs/node/pull/11624). * The new `util.promisify()` API has been added [[`99da8e8e02`](https://github.com/nodejs/node/commit/99da8e8e02)] [#12442](https://github.com/nodejs/node/pull/12442). * **Zlib** * Support `Uint8Array` in Zlib convenience methods [[`91383e47fd`](https://github.com/nodejs/node/commit/91383e47fd)] [#12001](https://github.com/nodejs/node/pull/12001). * Zlib errors now use `RangeError` and `TypeError` consistently [[`b514bd231e`](https://github.com/nodejs/node/commit/b514bd231e)] [#11391](https://github.com/nodejs/node/pull/11391).
2017-03-16 04:26:14 +01:00
added: v8.0.0
-->
* `err` {Error} A possible error.
* `callback` {Function} A callback function that takes an optional error
argument.
The `_destroy()` method is called by [`writable.destroy()`][writable-destroy].
It can be overridden by child classes but it **must not** be called directly.
#### `writable._final(callback)`
<!-- YAML
2017-05-30, Version 8.0.0 (Current) * **Async Hooks** * The `async_hooks` module has landed in core [[`4a7233c178`](https://github.com/nodejs/node/commit/4a7233c178)] [#12892](https://github.com/nodejs/node/pull/12892). * **Buffer** * Using the `--pending-deprecation` flag will cause Node.js to emit a deprecation warning when using `new Buffer(num)` or `Buffer(num)`. [[`d2d32ea5a2`](https://github.com/nodejs/node/commit/d2d32ea5a2)] [#11968](https://github.com/nodejs/node/pull/11968). * `new Buffer(num)` and `Buffer(num)` will zero-fill new `Buffer` instances [[`7eb1b4658e`](https://github.com/nodejs/node/commit/7eb1b4658e)] [#12141](https://github.com/nodejs/node/pull/12141). * Many `Buffer` methods now accept `Uint8Array` as input [[`beca3244e2`](https://github.com/nodejs/node/commit/beca3244e2)] [#10236](https://github.com/nodejs/node/pull/10236). * **Child Process** * Argument and kill signal validations have been improved [[`97a77288ce`](https://github.com/nodejs/node/commit/97a77288ce)] [#12348](https://github.com/nodejs/node/pull/12348), [[`d75fdd96aa`](https://github.com/nodejs/node/commit/d75fdd96aa)] [#10423](https://github.com/nodejs/node/pull/10423). * Child Process methods accept `Uint8Array` as input [[`627ecee9ed`](https://github.com/nodejs/node/commit/627ecee9ed)] [#10653](https://github.com/nodejs/node/pull/10653). * **Console** * Error events emitted when using `console` methods are now supressed. [[`f18e08d820`](https://github.com/nodejs/node/commit/f18e08d820)] [#9744](https://github.com/nodejs/node/pull/9744). * **Dependencies** * The npm client has been updated to 5.0.0 [[`3c3b36af0f`](https://github.com/nodejs/node/commit/3c3b36af0f)] [#12936](https://github.com/nodejs/node/pull/12936). * V8 has been updated to 5.8 with forward ABI stability to 6.0 [[`60d1aac8d2`](https://github.com/nodejs/node/commit/60d1aac8d2)] [#12784](https://github.com/nodejs/node/pull/12784). * **Domains** * Native `Promise` instances are now `Domain` aware [[`84dabe8373`](https://github.com/nodejs/node/commit/84dabe8373)] [#12489](https://github.com/nodejs/node/pull/12489). * **Errors** * We have started assigning static error codes to errors generated by Node.js. This has been done through multiple commits and is still a work in progress. * **File System** * The utility class `fs.SyncWriteStream` has been deprecated [[`7a55e34ef4`](https://github.com/nodejs/node/commit/7a55e34ef4)] [#10467](https://github.com/nodejs/node/pull/10467). * The deprecated `fs.read()` string interface has been removed [[`3c2a9361ff`](https://github.com/nodejs/node/commit/3c2a9361ff)] [#9683](https://github.com/nodejs/node/pull/9683). * **HTTP** * Improved support for userland implemented Agents [[`90403dd1d0`](https://github.com/nodejs/node/commit/90403dd1d0)] [#11567](https://github.com/nodejs/node/pull/11567). * Outgoing Cookie headers are concatenated into a single string [[`d3480776c7`](https://github.com/nodejs/node/commit/d3480776c7)] [#11259](https://github.com/nodejs/node/pull/11259). * The `httpResponse.writeHeader()` method has been deprecated [[`fb71ba4921`](https://github.com/nodejs/node/commit/fb71ba4921)] [#11355](https://github.com/nodejs/node/pull/11355). * New methods for accessing HTTP headers have been added to `OutgoingMessage` [[`3e6f1032a4`](https://github.com/nodejs/node/commit/3e6f1032a4)] [#10805](https://github.com/nodejs/node/pull/10805). * **Lib** * All deprecation messages have been assigned static identifiers [[`5de3cf099c`](https://github.com/nodejs/node/commit/5de3cf099c)] [#10116](https://github.com/nodejs/node/pull/10116). * The legacy `linkedlist` module has been removed [[`84a23391f6`](https://github.com/nodejs/node/commit/84a23391f6)] [#12113](https://github.com/nodejs/node/pull/12113). * **N-API** * Experimental support for the new N-API API has been added [[`56e881d0b0`](https://github.com/nodejs/node/commit/56e881d0b0)] [#11975](https://github.com/nodejs/node/pull/11975). * **Process** * Process warning output can be redirected to a file using the `--redirect-warnings` command-line argument [[`03e89b3ff2`](https://github.com/nodejs/node/commit/03e89b3ff2)] [#10116](https://github.com/nodejs/node/pull/10116). * Process warnings may now include additional detail [[`dd20e68b0f`](https://github.com/nodejs/node/commit/dd20e68b0f)] [#12725](https://github.com/nodejs/node/pull/12725). * **REPL** * REPL magic mode has been deprecated [[`3f27f02da0`](https://github.com/nodejs/node/commit/3f27f02da0)] [#11599](https://github.com/nodejs/node/pull/11599). * **Src** * `NODE_MODULE_VERSION` has been updated to 57 (https://github.com/nodejs/node/commit/ec7cbaf266)] [#12995](https://github.com/nodejs/node/pull/12995). * Add `--pending-deprecation` command-line argument and `NODE_PENDING_DEPRECATION` environment variable [[`a16b570f8c`](https://github.com/nodejs/node/commit/a16b570f8c)] [#11968](https://github.com/nodejs/node/pull/11968). * The `--debug` command-line argument has been deprecated. Note that using `--debug` will enable the *new* Inspector-based debug protocol as the legacy Debugger protocol previously used by Node.js has been removed. [[`010f864426`](https://github.com/nodejs/node/commit/010f864426)] [#12949](https://github.com/nodejs/node/pull/12949). * Throw when the `-c` and `-e` command-line arguments are used at the same time [[`a5f91ab230`](https://github.com/nodejs/node/commit/a5f91ab230)] [#11689](https://github.com/nodejs/node/pull/11689). * Throw when the `--use-bundled-ca` and `--use-openssl-ca` command-line arguments are used at the same time. [[`8a7db9d4b5`](https://github.com/nodejs/node/commit/8a7db9d4b5)] [#12087](https://github.com/nodejs/node/pull/12087). * **Stream** * `Stream` now supports `destroy()` and `_destroy()` APIs [[`b6e1d22fa6`](https://github.com/nodejs/node/commit/b6e1d22fa6)] [#12925](https://github.com/nodejs/node/pull/12925). * `Stream` now supports the `_final()` API [[`07c7f198db`](https://github.com/nodejs/node/commit/07c7f198db)] [#12828](https://github.com/nodejs/node/pull/12828). * **TLS** * The `rejectUnauthorized` option now defaults to `true` [[`348cc80a3c`](https://github.com/nodejs/node/commit/348cc80a3c)] [#5923](https://github.com/nodejs/node/pull/5923). * The `tls.createSecurePair()` API now emits a runtime deprecation [[`a2ae08999b`](https://github.com/nodejs/node/commit/a2ae08999b)] [#11349](https://github.com/nodejs/node/pull/11349). * A runtime deprecation will now be emitted when `dhparam` is less than 2048 bits [[`d523eb9c40`](https://github.com/nodejs/node/commit/d523eb9c40)] [#11447](https://github.com/nodejs/node/pull/11447). * **URL** * The WHATWG URL implementation is now a fully-supported Node.js API [[`d080ead0f9`](https://github.com/nodejs/node/commit/d080ead0f9)] [#12710](https://github.com/nodejs/node/pull/12710). * **Util** * `Symbol` keys are now displayed by default when using `util.inspect()` [[`5bfd13b81e`](https://github.com/nodejs/node/commit/5bfd13b81e)] [#9726](https://github.com/nodejs/node/pull/9726). * `toJSON` errors will be thrown when formatting `%j` [[`455e6f1dd8`](https://github.com/nodejs/node/commit/455e6f1dd8)] [#11708](https://github.com/nodejs/node/pull/11708). * Convert `inspect.styles` and `inspect.colors` to prototype-less objects [[`aab0d202f8`](https://github.com/nodejs/node/commit/aab0d202f8)] [#11624](https://github.com/nodejs/node/pull/11624). * The new `util.promisify()` API has been added [[`99da8e8e02`](https://github.com/nodejs/node/commit/99da8e8e02)] [#12442](https://github.com/nodejs/node/pull/12442). * **Zlib** * Support `Uint8Array` in Zlib convenience methods [[`91383e47fd`](https://github.com/nodejs/node/commit/91383e47fd)] [#12001](https://github.com/nodejs/node/pull/12001). * Zlib errors now use `RangeError` and `TypeError` consistently [[`b514bd231e`](https://github.com/nodejs/node/commit/b514bd231e)] [#11391](https://github.com/nodejs/node/pull/11391).
2017-03-16 04:26:14 +01:00
added: v8.0.0
-->
* `callback` {Function} Call this function (optionally with an error
argument) when finished writing any remaining data.
The `_final()` method **must not** be called directly. It may be implemented
by child classes, and if so, will be called by the internal `Writable`
class methods only.
This optional function will be called before the stream closes, delaying the
`'finish'` event until `callback` is called. This is useful to close resources
or write buffered data before a stream ends.
#### Errors while writing
Errors occurring during the processing of the [`writable._write()`][],
[`writable._writev()`][] and [`writable._final()`][] methods must be propagated
by invoking the callback and passing the error as the first argument.
Throwing an `Error` from within these methods or manually emitting an `'error'`
event results in undefined behavior.
If a `Readable` stream pipes into a `Writable` stream when `Writable` emits an
error, the `Readable` stream will be unpiped.
```js
const { Writable } = require('stream');
const myWritable = new Writable({
write(chunk, encoding, callback) {
if (chunk.toString().indexOf('a') >= 0) {
callback(new Error('chunk is invalid'));
} else {
callback();
}
}
});
```
#### An example writable stream
The following illustrates a rather simplistic (and somewhat pointless) custom
`Writable` stream implementation. While this specific `Writable` stream instance
is not of any real particular usefulness, the example illustrates each of the
required elements of a custom [`Writable`][] stream instance:
```js
const { Writable } = require('stream');
class MyWritable extends Writable {
_write(chunk, encoding, callback) {
if (chunk.toString().indexOf('a') >= 0) {
callback(new Error('chunk is invalid'));
} else {
callback();
}
}
}
```
#### Decoding buffers in a writable stream
Decoding buffers is a common task, for instance, when using transformers whose
input is a string. This is not a trivial process when using multi-byte
characters encoding, such as UTF-8. The following example shows how to decode
multi-byte strings using `StringDecoder` and [`Writable`][].
```js
const { Writable } = require('stream');
const { StringDecoder } = require('string_decoder');
class StringWritable extends Writable {
constructor(options) {
super(options);
this._decoder = new StringDecoder(options && options.defaultEncoding);
this.data = '';
}
_write(chunk, encoding, callback) {
if (encoding === 'buffer') {
chunk = this._decoder.write(chunk);
}
this.data += chunk;
callback();
}
_final(callback) {
this.data += this._decoder.end();
callback();
}
}
const euro = [[0xE2, 0x82], [0xAC]].map(Buffer.from);
const w = new StringWritable();
w.write('currency: ');
w.write(euro[0]);
w.end(euro[1]);
console.log(w.data); // currency: €
```
### Implementing a readable stream
The `stream.Readable` class is extended to implement a [`Readable`][] stream.
Custom `Readable` streams *must* call the `new stream.Readable([options])`
constructor and implement the [`readable._read()`][] method.
#### `new stream.Readable([options])`
<!-- YAML
changes:
- version:
- v11.2.0
- v10.16.0
pr-url: https://github.com/nodejs/node/pull/22795
description: Add `autoDestroy` option to automatically `destroy()` the
stream when it emits `'end'` or errors.
2020-04-21, Version 14.0.0 (Current) Deprecations: - (SEMVER-MAJOR) crypto: move pbkdf2 without digest to EOL (James M Snell) [#31166](https://github.com/nodejs/node/pull/31166) - (SEMVER-MAJOR) fs: deprecate closing FileHandle on garbage collection (James M Snell) [#28396](https://github.com/nodejs/node/pull/28396) - (SEMVER-MAJOR) http: move OutboundMessage.prototype.flush to EOL (James M Snell) [#31164](https://github.com/nodejs/node/pull/31164) - (SEMVER-MAJOR) lib: move GLOBAL and root aliases to EOL (James M Snell) [#31167](https://github.com/nodejs/node/pull/31167) - (SEMVER-MAJOR) os: move tmpDir() to EOL (James M Snell)[#31169](https://github.com/nodejs/node/pull/31169) - (SEMVER-MAJOR) src: remove deprecated wasm type check (Clemens Backes) [#32116](https://github.com/nodejs/node/pull/32116) - (SEMVER-MAJOR) stream: move \_writableState.buffer to EOL (James M Snell) [#31165](https://github.com/nodejs/node/pull/31165) - (SEMVER-MINOR) doc: deprecate process.mainModule (Antoine du HAMEL) [#32232](https://github.com/nodejs/node/pull/32232) - (SEMVER-MINOR) doc: deprecate process.umask() with no arguments (Colin Ihrig) [#32499](https://github.com/nodejs/node/pull/32499) ECMAScript Modules - Experimental Warning Removal: - module: remove experimental modules warning (Guy Bedford) [#31974](https://github.com/nodejs/node/pull/31974) In Node.js 13 we removed the need to include the --experimental-modules flag, but when running EcmaScript Modules in Node.js, this would still result in a warning ExperimentalWarning: The ESM module loader is experimental. As of Node.js 14 there is no longer this warning when using ESM in Node.js. However, the ESM implementation in Node.js remains experimental. As per our stability index: “The feature is not subject to Semantic Versioning rules. Non-backward compatible changes or removal may occur in any future release.” Users should be cautious when using the feature in production environments. Please keep in mind that the implementation of ESM in Node.js differs from the developer experience you might be familiar with. Most transpilation workflows support features such as optional file extensions or JSON modules that the Node.js ESM implementation does not support. It is highly likely that modules from transpiled environments will require a certain degree of refactoring to work in Node.js. It is worth mentioning that many of our design decisions were made with two primary goals. Spec compliance and Web Compatibility. It is our belief that the current implementation offers a future proof model to authoring ESM modules that paves the path to Universal JavaScript. Please read more in our documentation. The ESM implementation in Node.js is still experimental but we do believe that we are getting very close to being able to call ESM in Node.js “stable”. Removing the warning is a huge step in that direction. New V8 ArrayBuffer API: * **src**: migrate to new V8 ArrayBuffer API (Thang Tran) [#30782](https://github.com/nodejs/node/pull/30782) Multiple ArrayBuffers pointing to the same base address are no longer allowed by V8. This may impact native addons. Toolchain and Compiler Upgrades: - (SEMVER-MAJOR) build: update macos deployment target to 10.13 for 14.x (AshCripps)[#32454](https://github.com/nodejs/node/pull/32454) - (SEMVER-MAJOR) doc: update cross compiler machine for Linux armv7 (Richard Lau) [#32812](https://github.com/nodejs/node/pull/32812) - (SEMVER-MAJOR) doc: update Centos/RHEL releases use devtoolset-8 (Richard Lau) [#32812](https://github.com/nodejs/node/pull/32812) - (SEMVER-MAJOR) doc: remove SmartOS from official binaries (Richard Lau) [#32812](https://github.com/nodejs/node/pull/32812) - (SEMVER-MAJOR) win: block running on EOL Windows versions (João Reis) [#31954](https://github.com/nodejs/node/pull/31954) It is expected that there will be an ABI mismatch on ARM between the Node.js binary and native addons. Native addons are only broken if they interact with `std::shared_ptr`. This is expected to be fixed in a later version of Node.js 14. - [#30786](https://github.com/nodejs/node/issues/30786) Update to V8 8.1: - (SEMVER-MAJOR) deps: update V8 to 8.1.307.20 (Matheus Marchini) [#32116](https://github.com/nodejs/node/pull/32116) Other Notable Changes: - cli, report: move --report-on-fatalerror to stable (Colin Ihrig) [#32496](https://github.com/nodejs/node/pull/32496) - deps: upgrade to libuv 1.37.0 (Colin Ihrig) [#32866](https://github.com/nodejs/node/pull/32866) - fs: add fs/promises alias module (Gus Caplan) [#31553](https://github.com/nodejs/node/pull/31553) PR-URL: https://github.com/nodejs/node/pull/32181
2020-03-10 18:16:08 +01:00
- version: v14.0.0
pr-url: https://github.com/nodejs/node/pull/30623
description: Change `autoDestroy` option default to `true`.
-->
* `options` {Object}
* `highWaterMark` {number} The maximum [number of bytes][hwm-gotcha] to store
in the internal buffer before ceasing to read from the underlying resource.
**Default:** `16384` (16KB), or `16` for `objectMode` streams.
* `encoding` {string} If specified, then buffers will be decoded to
strings using the specified encoding. **Default:** `null`.
* `objectMode` {boolean} Whether this stream should behave
as a stream of objects. Meaning that [`stream.read(n)`][stream-read] returns
a single value instead of a `Buffer` of size `n`. **Default:** `false`.
* `emitClose` {boolean} Whether or not the stream should emit `'close'`
after it has been destroyed. **Default:** `true`.
* `read` {Function} Implementation for the [`stream._read()`][stream-_read]
method.
* `destroy` {Function} Implementation for the
[`stream._destroy()`][readable-_destroy] method.
* `construct` {Function} Implementation for the
[`stream._construct()`][readable-_construct] method.
* `autoDestroy` {boolean} Whether this stream should automatically call
`.destroy()` on itself after ending. **Default:** `true`.
<!-- eslint-disable no-useless-constructor -->
```js
const { Readable } = require('stream');
class MyReadable extends Readable {
constructor(options) {
// Calls the stream.Readable(options) constructor.
super(options);
// ...
}
}
```
Or, when using pre-ES6 style constructors:
```js
const { Readable } = require('stream');
const util = require('util');
function MyReadable(options) {
if (!(this instanceof MyReadable))
return new MyReadable(options);
Readable.call(this, options);
}
util.inherits(MyReadable, Readable);
```
Or, using the simplified constructor approach:
```js
const { Readable } = require('stream');
const myReadable = new Readable({
read(size) {
// ...
}
});
```
#### `readable._construct(callback)`
<!-- YAML
added: REPLACEME
-->
* `callback` {Function} Call this function (optionally with an error
argument) when the stream has finished initializing.
The `_construct()` method MUST NOT be called directly. It may be implemented
by child classes, and if so, will be called by the internal `Readable`
class methods only.
This optional function will be scheduled in the next tick by the stream
constructor, delaying any `_read` and `_destroy` calls until `callback` is
called. This is useful to initialize state or asynchronously initialize
resources before the stream can be used.
```js
const { Readable } = require('stream');
const fs = require('fs');
class ReadStream extends Readable {
constructor(filename) {
super();
this.filename = filename;
this.fd = null;
}
_construct(callback) {
fs.open(this.filename, (fd, err) => {
if (err) {
callback(err);
} else {
this.fd = fd;
callback();
}
});
}
_read(n) {
const buf = Buffer.alloc(n);
fs.read(this.fd, buf, 0, n, null, (err, bytesRead) => {
if (err) {
this.destroy(err);
} else {
this.push(bytesRead > 0 ? buf.slice(0, bytesRead) : null);
}
});
}
_destroy(err, callback) {
if (this.fd) {
fs.close(this.fd, (er) => callback(er || err));
} else {
callback(err);
}
}
}
```
#### `readable._read(size)`
<!-- YAML
added: v0.9.4
-->
* `size` {number} Number of bytes to read asynchronously
This function MUST NOT be called by application code directly. It should be
implemented by child classes, and called by the internal `Readable` class
methods only.
All `Readable` stream implementations must provide an implementation of the
[`readable._read()`][] method to fetch data from the underlying resource.
When [`readable._read()`][] is called, if data is available from the resource,
the implementation should begin pushing that data into the read queue using the
[`this.push(dataChunk)`][stream-push] method. `_read()` should continue reading
from the resource and pushing data until `readable.push()` returns `false`. Only
when `_read()` is called again after it has stopped should it resume pushing
additional data onto the queue.
Once the [`readable._read()`][] method has been called, it will not be called
again until more data is pushed through the [`readable.push()`][stream-push]
method. Empty data such as empty buffers and strings will not cause
[`readable._read()`][] to be called.
The `size` argument is advisory. For implementations where a "read" is a
single operation that returns data can use the `size` argument to determine how
much data to fetch. Other implementations may ignore this argument and simply
provide data whenever it becomes available. There is no need to "wait" until
`size` bytes are available before calling [`stream.push(chunk)`][stream-push].
The [`readable._read()`][] method is prefixed with an underscore because it is
internal to the class that defines it, and should never be called directly by
user programs.
#### `readable._destroy(err, callback)`
<!-- YAML
added: v8.0.0
-->
* `err` {Error} A possible error.
* `callback` {Function} A callback function that takes an optional error
argument.
The `_destroy()` method is called by [`readable.destroy()`][readable-destroy].
It can be overridden by child classes but it **must not** be called directly.
#### `readable.push(chunk[, encoding])`
<!-- YAML
changes:
2017-05-30, Version 8.0.0 (Current) * **Async Hooks** * The `async_hooks` module has landed in core [[`4a7233c178`](https://github.com/nodejs/node/commit/4a7233c178)] [#12892](https://github.com/nodejs/node/pull/12892). * **Buffer** * Using the `--pending-deprecation` flag will cause Node.js to emit a deprecation warning when using `new Buffer(num)` or `Buffer(num)`. [[`d2d32ea5a2`](https://github.com/nodejs/node/commit/d2d32ea5a2)] [#11968](https://github.com/nodejs/node/pull/11968). * `new Buffer(num)` and `Buffer(num)` will zero-fill new `Buffer` instances [[`7eb1b4658e`](https://github.com/nodejs/node/commit/7eb1b4658e)] [#12141](https://github.com/nodejs/node/pull/12141). * Many `Buffer` methods now accept `Uint8Array` as input [[`beca3244e2`](https://github.com/nodejs/node/commit/beca3244e2)] [#10236](https://github.com/nodejs/node/pull/10236). * **Child Process** * Argument and kill signal validations have been improved [[`97a77288ce`](https://github.com/nodejs/node/commit/97a77288ce)] [#12348](https://github.com/nodejs/node/pull/12348), [[`d75fdd96aa`](https://github.com/nodejs/node/commit/d75fdd96aa)] [#10423](https://github.com/nodejs/node/pull/10423). * Child Process methods accept `Uint8Array` as input [[`627ecee9ed`](https://github.com/nodejs/node/commit/627ecee9ed)] [#10653](https://github.com/nodejs/node/pull/10653). * **Console** * Error events emitted when using `console` methods are now supressed. [[`f18e08d820`](https://github.com/nodejs/node/commit/f18e08d820)] [#9744](https://github.com/nodejs/node/pull/9744). * **Dependencies** * The npm client has been updated to 5.0.0 [[`3c3b36af0f`](https://github.com/nodejs/node/commit/3c3b36af0f)] [#12936](https://github.com/nodejs/node/pull/12936). * V8 has been updated to 5.8 with forward ABI stability to 6.0 [[`60d1aac8d2`](https://github.com/nodejs/node/commit/60d1aac8d2)] [#12784](https://github.com/nodejs/node/pull/12784). * **Domains** * Native `Promise` instances are now `Domain` aware [[`84dabe8373`](https://github.com/nodejs/node/commit/84dabe8373)] [#12489](https://github.com/nodejs/node/pull/12489). * **Errors** * We have started assigning static error codes to errors generated by Node.js. This has been done through multiple commits and is still a work in progress. * **File System** * The utility class `fs.SyncWriteStream` has been deprecated [[`7a55e34ef4`](https://github.com/nodejs/node/commit/7a55e34ef4)] [#10467](https://github.com/nodejs/node/pull/10467). * The deprecated `fs.read()` string interface has been removed [[`3c2a9361ff`](https://github.com/nodejs/node/commit/3c2a9361ff)] [#9683](https://github.com/nodejs/node/pull/9683). * **HTTP** * Improved support for userland implemented Agents [[`90403dd1d0`](https://github.com/nodejs/node/commit/90403dd1d0)] [#11567](https://github.com/nodejs/node/pull/11567). * Outgoing Cookie headers are concatenated into a single string [[`d3480776c7`](https://github.com/nodejs/node/commit/d3480776c7)] [#11259](https://github.com/nodejs/node/pull/11259). * The `httpResponse.writeHeader()` method has been deprecated [[`fb71ba4921`](https://github.com/nodejs/node/commit/fb71ba4921)] [#11355](https://github.com/nodejs/node/pull/11355). * New methods for accessing HTTP headers have been added to `OutgoingMessage` [[`3e6f1032a4`](https://github.com/nodejs/node/commit/3e6f1032a4)] [#10805](https://github.com/nodejs/node/pull/10805). * **Lib** * All deprecation messages have been assigned static identifiers [[`5de3cf099c`](https://github.com/nodejs/node/commit/5de3cf099c)] [#10116](https://github.com/nodejs/node/pull/10116). * The legacy `linkedlist` module has been removed [[`84a23391f6`](https://github.com/nodejs/node/commit/84a23391f6)] [#12113](https://github.com/nodejs/node/pull/12113). * **N-API** * Experimental support for the new N-API API has been added [[`56e881d0b0`](https://github.com/nodejs/node/commit/56e881d0b0)] [#11975](https://github.com/nodejs/node/pull/11975). * **Process** * Process warning output can be redirected to a file using the `--redirect-warnings` command-line argument [[`03e89b3ff2`](https://github.com/nodejs/node/commit/03e89b3ff2)] [#10116](https://github.com/nodejs/node/pull/10116). * Process warnings may now include additional detail [[`dd20e68b0f`](https://github.com/nodejs/node/commit/dd20e68b0f)] [#12725](https://github.com/nodejs/node/pull/12725). * **REPL** * REPL magic mode has been deprecated [[`3f27f02da0`](https://github.com/nodejs/node/commit/3f27f02da0)] [#11599](https://github.com/nodejs/node/pull/11599). * **Src** * `NODE_MODULE_VERSION` has been updated to 57 (https://github.com/nodejs/node/commit/ec7cbaf266)] [#12995](https://github.com/nodejs/node/pull/12995). * Add `--pending-deprecation` command-line argument and `NODE_PENDING_DEPRECATION` environment variable [[`a16b570f8c`](https://github.com/nodejs/node/commit/a16b570f8c)] [#11968](https://github.com/nodejs/node/pull/11968). * The `--debug` command-line argument has been deprecated. Note that using `--debug` will enable the *new* Inspector-based debug protocol as the legacy Debugger protocol previously used by Node.js has been removed. [[`010f864426`](https://github.com/nodejs/node/commit/010f864426)] [#12949](https://github.com/nodejs/node/pull/12949). * Throw when the `-c` and `-e` command-line arguments are used at the same time [[`a5f91ab230`](https://github.com/nodejs/node/commit/a5f91ab230)] [#11689](https://github.com/nodejs/node/pull/11689). * Throw when the `--use-bundled-ca` and `--use-openssl-ca` command-line arguments are used at the same time. [[`8a7db9d4b5`](https://github.com/nodejs/node/commit/8a7db9d4b5)] [#12087](https://github.com/nodejs/node/pull/12087). * **Stream** * `Stream` now supports `destroy()` and `_destroy()` APIs [[`b6e1d22fa6`](https://github.com/nodejs/node/commit/b6e1d22fa6)] [#12925](https://github.com/nodejs/node/pull/12925). * `Stream` now supports the `_final()` API [[`07c7f198db`](https://github.com/nodejs/node/commit/07c7f198db)] [#12828](https://github.com/nodejs/node/pull/12828). * **TLS** * The `rejectUnauthorized` option now defaults to `true` [[`348cc80a3c`](https://github.com/nodejs/node/commit/348cc80a3c)] [#5923](https://github.com/nodejs/node/pull/5923). * The `tls.createSecurePair()` API now emits a runtime deprecation [[`a2ae08999b`](https://github.com/nodejs/node/commit/a2ae08999b)] [#11349](https://github.com/nodejs/node/pull/11349). * A runtime deprecation will now be emitted when `dhparam` is less than 2048 bits [[`d523eb9c40`](https://github.com/nodejs/node/commit/d523eb9c40)] [#11447](https://github.com/nodejs/node/pull/11447). * **URL** * The WHATWG URL implementation is now a fully-supported Node.js API [[`d080ead0f9`](https://github.com/nodejs/node/commit/d080ead0f9)] [#12710](https://github.com/nodejs/node/pull/12710). * **Util** * `Symbol` keys are now displayed by default when using `util.inspect()` [[`5bfd13b81e`](https://github.com/nodejs/node/commit/5bfd13b81e)] [#9726](https://github.com/nodejs/node/pull/9726). * `toJSON` errors will be thrown when formatting `%j` [[`455e6f1dd8`](https://github.com/nodejs/node/commit/455e6f1dd8)] [#11708](https://github.com/nodejs/node/pull/11708). * Convert `inspect.styles` and `inspect.colors` to prototype-less objects [[`aab0d202f8`](https://github.com/nodejs/node/commit/aab0d202f8)] [#11624](https://github.com/nodejs/node/pull/11624). * The new `util.promisify()` API has been added [[`99da8e8e02`](https://github.com/nodejs/node/commit/99da8e8e02)] [#12442](https://github.com/nodejs/node/pull/12442). * **Zlib** * Support `Uint8Array` in Zlib convenience methods [[`91383e47fd`](https://github.com/nodejs/node/commit/91383e47fd)] [#12001](https://github.com/nodejs/node/pull/12001). * Zlib errors now use `RangeError` and `TypeError` consistently [[`b514bd231e`](https://github.com/nodejs/node/commit/b514bd231e)] [#11391](https://github.com/nodejs/node/pull/11391).
2017-03-16 04:26:14 +01:00
- version: v8.0.0
pr-url: https://github.com/nodejs/node/pull/11608
description: The `chunk` argument can now be a `Uint8Array` instance.
-->
* `chunk` {Buffer|Uint8Array|string|null|any} Chunk of data to push into the
read queue. For streams not operating in object mode, `chunk` must be a
string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be
any JavaScript value.
* `encoding` {string} Encoding of string chunks. Must be a valid
`Buffer` encoding, such as `'utf8'` or `'ascii'`.
* Returns: {boolean} `true` if additional chunks of data may continue to be
pushed; `false` otherwise.
When `chunk` is a `Buffer`, `Uint8Array` or `string`, the `chunk` of data will
be added to the internal queue for users of the stream to consume.
Passing `chunk` as `null` signals the end of the stream (EOF), after which no
more data can be written.
When the `Readable` is operating in paused mode, the data added with
`readable.push()` can be read out by calling the
[`readable.read()`][stream-read] method when the [`'readable'`][] event is
emitted.
When the `Readable` is operating in flowing mode, the data added with
`readable.push()` will be delivered by emitting a `'data'` event.
The `readable.push()` method is designed to be as flexible as possible. For
example, when wrapping a lower-level source that provides some form of
pause/resume mechanism, and a data callback, the low-level source can be wrapped
by the custom `Readable` instance:
```js
// `_source` is an object with readStop() and readStart() methods,
// and an `ondata` member that gets called when it has data, and
// an `onend` member that gets called when the data is over.
class SourceWrapper extends Readable {
constructor(options) {
super(options);
this._source = getLowLevelSourceObject();
// Every time there's data, push it into the internal buffer.
this._source.ondata = (chunk) => {
// If push() returns false, then stop reading from source.
if (!this.push(chunk))
this._source.readStop();
};
// When the source ends, push the EOF-signaling `null` chunk.
this._source.onend = () => {
this.push(null);
};
}
// _read() will be called when the stream wants to pull more data in.
// The advisory size argument is ignored in this case.
_read(size) {
this._source.readStart();
}
}
```
The `readable.push()` method is used to push the content
into the internal buffer. It can be driven by the [`readable._read()`][] method.
For streams not operating in object mode, if the `chunk` parameter of
`readable.push()` is `undefined`, it will be treated as empty string or
buffer. See [`readable.push('')`][] for more information.
#### Errors while reading
Errors occurring during processing of the [`readable._read()`][] must be
propagated through the [`readable.destroy(err)`][readable-_destroy] method.
Throwing an `Error` from within [`readable._read()`][] or manually emitting an
`'error'` event results in undefined behavior.
```js
const { Readable } = require('stream');
const myReadable = new Readable({
read(size) {
const err = checkSomeErrorCondition();
if (err) {
this.destroy(err);
} else {
// Do some work.
}
}
});
```
#### An example counting stream
<!--type=example-->
The following is a basic example of a `Readable` stream that emits the numerals
from 1 to 1,000,000 in ascending order, and then ends.
```js
const { Readable } = require('stream');
class Counter extends Readable {
constructor(opt) {
super(opt);
this._max = 1000000;
this._index = 1;
}
_read() {
const i = this._index++;
if (i > this._max)
this.push(null);
else {
const str = String(i);
const buf = Buffer.from(str, 'ascii');
this.push(buf);
}
}
}
```
### Implementing a duplex stream
A [`Duplex`][] stream is one that implements both [`Readable`][] and
[`Writable`][], such as a TCP socket connection.
Because JavaScript does not have support for multiple inheritance, the
`stream.Duplex` class is extended to implement a [`Duplex`][] stream (as opposed
to extending the `stream.Readable` *and* `stream.Writable` classes).
The `stream.Duplex` class prototypically inherits from `stream.Readable` and
parasitically from `stream.Writable`, but `instanceof` will work properly for
both base classes due to overriding [`Symbol.hasInstance`][] on
`stream.Writable`.
Custom `Duplex` streams *must* call the `new stream.Duplex([options])`
constructor and implement *both* the [`readable._read()`][] and
`writable._write()` methods.
#### `new stream.Duplex(options)`
<!-- YAML
changes:
- version: v8.4.0
pr-url: https://github.com/nodejs/node/pull/14636
description: The `readableHighWaterMark` and `writableHighWaterMark` options
are supported now.
-->
* `options` {Object} Passed to both `Writable` and `Readable`
constructors. Also has the following fields:
* `allowHalfOpen` {boolean} If set to `false`, then the stream will
automatically end the writable side when the readable side ends.
**Default:** `true`.
* `readableObjectMode` {boolean} Sets `objectMode` for readable side of the
stream. Has no effect if `objectMode` is `true`. **Default:** `false`.
* `writableObjectMode` {boolean} Sets `objectMode` for writable side of the
stream. Has no effect if `objectMode` is `true`. **Default:** `false`.
* `readableHighWaterMark` {number} Sets `highWaterMark` for the readable side
of the stream. Has no effect if `highWaterMark` is provided.
* `writableHighWaterMark` {number} Sets `highWaterMark` for the writable side
of the stream. Has no effect if `highWaterMark` is provided.
<!-- eslint-disable no-useless-constructor -->
```js
const { Duplex } = require('stream');
class MyDuplex extends Duplex {
constructor(options) {
super(options);
// ...
}
}
```
Or, when using pre-ES6 style constructors:
2010-10-28 14:18:16 +02:00
```js
const { Duplex } = require('stream');
const util = require('util');
2010-10-28 14:18:16 +02:00
function MyDuplex(options) {
if (!(this instanceof MyDuplex))
return new MyDuplex(options);
Duplex.call(this, options);
}
util.inherits(MyDuplex, Duplex);
```
Or, using the simplified constructor approach:
```js
const { Duplex } = require('stream');
const myDuplex = new Duplex({
read(size) {
// ...
},
write(chunk, encoding, callback) {
// ...
}
});
```
2010-10-28 14:18:16 +02:00
When using pipeline:
```js
const { Transform, pipeline } = require('stream');
const fs = require('fs');
pipeline(
fs.createReadStream('object.json')
.setEncoding('utf-8'),
new Transform({
decodeStrings: false, // Accept string input rather than Buffers
construct(callback) {
this.data = '';
callback();
},
transform(chunk, encoding, callback) {
this.data += chunk;
callback();
},
flush(callback) {
try {
// Make sure is valid json.
JSON.parse(this.data);
this.push(this.data);
} catch (err) {
callback(err);
}
}
}),
fs.createWriteStream('valid-object.json'),
(err) => {
if (err) {
console.error('failed', err);
} else {
console.log('completed');
}
}
);
```
#### An example duplex stream
The following illustrates a simple example of a `Duplex` stream that wraps a
hypothetical lower-level source object to which data can be written, and
from which data can be read, albeit using an API that is not compatible with
Node.js streams.
The following illustrates a simple example of a `Duplex` stream that buffers
incoming written data via the [`Writable`][] interface that is read back out
via the [`Readable`][] interface.
```js
const { Duplex } = require('stream');
const kSource = Symbol('source');
class MyDuplex extends Duplex {
constructor(source, options) {
super(options);
this[kSource] = source;
}
_write(chunk, encoding, callback) {
// The underlying source only deals with strings.
if (Buffer.isBuffer(chunk))
chunk = chunk.toString();
this[kSource].writeSomeData(chunk);
callback();
}
_read(size) {
this[kSource].fetchSomeData(size, (data, encoding) => {
this.push(Buffer.from(data, encoding));
});
}
}
```
The most important aspect of a `Duplex` stream is that the `Readable` and
`Writable` sides operate independently of one another despite co-existing within
a single object instance.
2010-10-28 14:18:16 +02:00
#### Object mode duplex streams
For `Duplex` streams, `objectMode` can be set exclusively for either the
`Readable` or `Writable` side using the `readableObjectMode` and
`writableObjectMode` options respectively.
In the following example, for instance, a new `Transform` stream (which is a
type of [`Duplex`][] stream) is created that has an object mode `Writable` side
that accepts JavaScript numbers that are converted to hexadecimal strings on
the `Readable` side.
```js
const { Transform } = require('stream');
// All Transform streams are also Duplex Streams.
const myTransform = new Transform({
writableObjectMode: true,
transform(chunk, encoding, callback) {
// Coerce the chunk to a number if necessary.
chunk |= 0;
// Transform the chunk into something else.
const data = chunk.toString(16);
// Push the data onto the readable queue.
callback(null, '0'.repeat(data.length % 2) + data);
}
});
myTransform.setEncoding('ascii');
myTransform.on('data', (chunk) => console.log(chunk));
myTransform.write(1);
// Prints: 01
myTransform.write(10);
// Prints: 0a
myTransform.write(100);
// Prints: 64
```
### Implementing a transform stream
A [`Transform`][] stream is a [`Duplex`][] stream where the output is computed
in some way from the input. Examples include [zlib][] streams or [crypto][]
streams that compress, encrypt, or decrypt data.
There is no requirement that the output be the same size as the input, the same
number of chunks, or arrive at the same time. For example, a `Hash` stream will
only ever have a single chunk of output which is provided when the input is
ended. A `zlib` stream will produce output that is either much smaller or much
larger than its input.
The `stream.Transform` class is extended to implement a [`Transform`][] stream.
The `stream.Transform` class prototypically inherits from `stream.Duplex` and
implements its own versions of the `writable._write()` and
[`readable._read()`][] methods. Custom `Transform` implementations *must*
implement the [`transform._transform()`][stream-_transform] method and *may*
also implement the [`transform._flush()`][stream-_flush] method.
Care must be taken when using `Transform` streams in that data written to the
stream can cause the `Writable` side of the stream to become paused if the
output on the `Readable` side is not consumed.
#### `new stream.Transform([options])`
* `options` {Object} Passed to both `Writable` and `Readable`
constructors. Also has the following fields:
* `transform` {Function} Implementation for the
[`stream._transform()`][stream-_transform] method.
* `flush` {Function} Implementation for the [`stream._flush()`][stream-_flush]
method.
<!-- eslint-disable no-useless-constructor -->
```js
const { Transform } = require('stream');
class MyTransform extends Transform {
constructor(options) {
super(options);
// ...
}
}
```
Or, when using pre-ES6 style constructors:
```js
const { Transform } = require('stream');
const util = require('util');
function MyTransform(options) {
if (!(this instanceof MyTransform))
return new MyTransform(options);
Transform.call(this, options);
}
util.inherits(MyTransform, Transform);
```
Or, using the simplified constructor approach:
```js
const { Transform } = require('stream');
const myTransform = new Transform({
transform(chunk, encoding, callback) {
// ...
}
});
```
#### Event: `'end'`
The [`'end'`][] event is from the `stream.Readable` class. The `'end'` event is
emitted after all data has been output, which occurs after the callback in
[`transform._flush()`][stream-_flush] has been called. In the case of an error,
`'end'` should not be emitted.
#### Event: `'finish'`
The [`'finish'`][] event is from the `stream.Writable` class. The `'finish'`
event is emitted after [`stream.end()`][stream-end] is called and all chunks
have been processed by [`stream._transform()`][stream-_transform]. In the case
of an error, `'finish'` should not be emitted.
#### `transform._flush(callback)`
* `callback` {Function} A callback function (optionally with an error
argument and data) to be called when remaining data has been flushed.
This function MUST NOT be called by application code directly. It should be
implemented by child classes, and called by the internal `Readable` class
methods only.
In some cases, a transform operation may need to emit an additional bit of
data at the end of the stream. For example, a `zlib` compression stream will
store an amount of internal state used to optimally compress the output. When
the stream ends, however, that additional data needs to be flushed so that the
compressed data will be complete.
Custom [`Transform`][] implementations *may* implement the `transform._flush()`
method. This will be called when there is no more written data to be consumed,
but before the [`'end'`][] event is emitted signaling the end of the
[`Readable`][] stream.
Within the `transform._flush()` implementation, the `readable.push()` method
may be called zero or more times, as appropriate. The `callback` function must
be called when the flush operation is complete.
The `transform._flush()` method is prefixed with an underscore because it is
internal to the class that defines it, and should never be called directly by
user programs.
#### `transform._transform(chunk, encoding, callback)`
* `chunk` {Buffer|string|any} The `Buffer` to be transformed, converted from
the `string` passed to [`stream.write()`][stream-write]. If the stream's
`decodeStrings` option is `false` or the stream is operating in object mode,
the chunk will not be converted & will be whatever was passed to
[`stream.write()`][stream-write].
* `encoding` {string} If the chunk is a string, then this is the
encoding type. If chunk is a buffer, then this is the special
value `'buffer'`. Ignore it in that case.
* `callback` {Function} A callback function (optionally with an error
argument and data) to be called after the supplied `chunk` has been
processed.
This function MUST NOT be called by application code directly. It should be
implemented by child classes, and called by the internal `Readable` class
methods only.
All `Transform` stream implementations must provide a `_transform()`
method to accept input and produce output. The `transform._transform()`
implementation handles the bytes being written, computes an output, then passes
that output off to the readable portion using the `readable.push()` method.
The `transform.push()` method may be called zero or more times to generate
output from a single input chunk, depending on how much is to be output
as 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
consumed. The first argument passed to the `callback` must be an `Error` object
if an error occurred while processing the input or `null` otherwise. If a second
argument is passed to the `callback`, it will be forwarded on to the
`readable.push()` method. In other words, the following are equivalent:
```js
transform.prototype._transform = function(data, encoding, callback) {
this.push(data);
callback();
};
transform.prototype._transform = function(data, encoding, callback) {
callback(null, data);
};
```
The `transform._transform()` method is prefixed with an underscore because it
is internal to the class that defines it, and should never be called directly by
user programs.
`transform._transform()` is never called in parallel; streams implement a
queue mechanism, and to receive the next chunk, `callback` must be
called, either synchronously or asynchronously.
#### Class: `stream.PassThrough`
The `stream.PassThrough` class is a trivial implementation of a [`Transform`][]
stream that simply passes the input bytes across to the output. Its purpose is
primarily for examples and testing, but there are some use cases where
`stream.PassThrough` is useful as a building block for novel sorts of streams.
## Additional notes
<!--type=misc-->
### Streams compatibility with async generators and async iterators
With the support of async generators and iterators in JavaScript, async
generators are effectively a first-class language-level stream construct at
this point.
Some common interop cases of using Node.js streams with async generators
and async iterators are provided below.
#### Consuming readable streams with async iterators
```js
(async function() {
for await (const chunk of readable) {
console.log(chunk);
}
})();
```
Async iterators register a permanent error handler on the stream to prevent any
unhandled post-destroy errors.
#### Creating readable streams with async generators
A Node.js readable stream can be created from an asynchronous generator using
the `Readable.from()` utility method:
```js
const { Readable } = require('stream');
async function * generate() {
yield 'a';
yield 'b';
yield 'c';
}
const readable = Readable.from(generate());
readable.on('data', (chunk) => {
console.log(chunk);
});
```
#### Piping to writable streams from async iterators
When writing to a writable stream from an async iterator, ensure correct
handling of backpressure and errors. [`stream.pipeline()`][] abstracts away
the handling of backpressure and backpressure-related errors:
```js
const { pipeline } = require('stream');
const util = require('util');
const fs = require('fs');
const writable = fs.createWriteStream('./file');
// Callback Pattern
pipeline(iterator, writable, (err, value) => {
if (err) {
console.error(err);
} else {
console.log(value, 'value returned');
}
});
// Promise Pattern
const pipelinePromise = util.promisify(pipeline);
pipelinePromise(iterator, writable)
.then((value) => {
console.log(value, 'value returned');
})
.catch(console.error);
```
<!--type=misc-->
### Compatibility with older Node.js versions
<!--type=misc-->
Prior to Node.js 0.10, the `Readable` stream interface was simpler, but also
less powerful and less useful.
* Rather than waiting for calls to the [`stream.read()`][stream-read] method,
[`'data'`][] events would begin emitting immediately. Applications that
would need to perform some amount of work to decide how to handle data
were required to store read data into buffers so the data would not be lost.
* The [`stream.pause()`][stream-pause] method was advisory, rather than
guaranteed. This meant that it was still necessary to be prepared to receive
[`'data'`][] events *even when the stream was in a paused state*.
In Node.js 0.10, the [`Readable`][] class was added. For backward
compatibility with older Node.js programs, `Readable` streams switch into
"flowing mode" when a [`'data'`][] event handler is added, or when the
[`stream.resume()`][stream-resume] method is called. The effect is that, even
when not using the new [`stream.read()`][stream-read] method and
[`'readable'`][] event, it is no longer necessary to worry about losing
[`'data'`][] chunks.
While most applications will continue to function normally, this introduces an
edge case in the following conditions:
* No [`'data'`][] event listener is added.
* The [`stream.resume()`][stream-resume] method is never called.
* The stream is not piped to any writable destination.
For example, consider the following code:
```js
// WARNING! BROKEN!
net.createServer((socket) => {
// We add an 'end' listener, but never consume the data.
socket.on('end', () => {
// It will never get here.
socket.end('The message was received but was not processed.\n');
});
}).listen(1337);
```
Prior to Node.js 0.10, the incoming message data would be simply discarded.
However, in Node.js 0.10 and beyond, the socket remains paused forever.
The workaround in this situation is to call the
[`stream.resume()`][stream-resume] method to begin the flow of data:
```js
// Workaround.
net.createServer((socket) => {
socket.on('end', () => {
socket.end('The message was received but was not processed.\n');
});
// Start the flow of data, discarding it.
socket.resume();
}).listen(1337);
```
In addition to new `Readable` streams switching into flowing mode,
pre-0.10 style streams can be wrapped in a `Readable` class using the
[`readable.wrap()`][`stream.wrap()`] method.
### `readable.read(0)`
There are some cases where it is necessary to trigger a refresh of the
underlying readable stream mechanisms, without actually consuming any
data. In such cases, it is possible to call `readable.read(0)`, which will
always return `null`.
If the internal read buffer is below the `highWaterMark`, and the
stream is not currently reading, then calling `stream.read(0)` will trigger
a low-level [`stream._read()`][stream-_read] call.
While most applications will almost never need to do this, there are
situations within Node.js where this is done, particularly in the
`Readable` stream class internals.
### `readable.push('')`
Use of `readable.push('')` is not recommended.
Pushing a zero-byte string, `Buffer` or `Uint8Array` to a stream that is not in
object mode has an interesting side effect. Because it *is* a call to
[`readable.push()`][stream-push], the call will end the reading process.
However, because the argument is an empty string, no data is added to the
readable buffer so there is nothing for a user to consume.
### `highWaterMark` discrepancy after calling `readable.setEncoding()`
The use of `readable.setEncoding()` will change the behavior of how the
`highWaterMark` operates in non-object mode.
Typically, the size of the current buffer is measured against the
`highWaterMark` in _bytes_. However, after `setEncoding()` is called, the
comparison function will begin to measure the buffer's size in _characters_.
This is not a problem in common cases with `latin1` or `ascii`. But it is
advised to be mindful about this behavior when working with strings that could
contain multi-byte characters.
[`'data'`]: #stream_event_data
[`'drain'`]: #stream_event_drain
[`'end'`]: #stream_event_end
[`'finish'`]: #stream_event_finish
[`'readable'`]: #stream_event_readable
[`Duplex`]: #stream_class_stream_duplex
[`EventEmitter`]: events.html#events_class_eventemitter
[`Readable`]: #stream_class_stream_readable
[`Symbol.hasInstance`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance
[`Transform`]: #stream_class_stream_transform
[`Writable`]: #stream_class_stream_writable
[`fs.createReadStream()`]: fs.html#fs_fs_createreadstream_path_options
[`fs.createWriteStream()`]: fs.html#fs_fs_createwritestream_path_options
[`net.Socket`]: net.html#net_class_net_socket
[`process.stderr`]: process.html#process_process_stderr
[`process.stdin`]: process.html#process_process_stdin
[`process.stdout`]: process.html#process_process_stdout
[`readable._read()`]: #stream_readable_read_size_1
[`readable.push('')`]: #stream_readable_push
[`readable.setEncoding()`]: #stream_readable_setencoding_encoding
[`stream.Readable.from()`]: #stream_stream_readable_from_iterable_options
[`stream.cork()`]: #stream_writable_cork
[`stream.finished()`]: #stream_stream_finished_stream_options_callback
[`stream.pipe()`]: #stream_readable_pipe_destination_options
[`stream.pipeline()`]: #stream_stream_pipeline_source_transforms_destination_callback
[`stream.uncork()`]: #stream_writable_uncork
[`stream.unpipe()`]: #stream_readable_unpipe_destination
[`stream.wrap()`]: #stream_readable_wrap_stream
[`writable._final()`]: #stream_writable_final_callback
[`writable._write()`]: #stream_writable_write_chunk_encoding_callback_1
[`writable._writev()`]: #stream_writable_writev_chunks_callback
[`writable.cork()`]: #stream_writable_cork
[`writable.end()`]: #stream_writable_end_chunk_encoding_callback
[`writable.uncork()`]: #stream_writable_uncork
[`writable.writableFinished`]: #stream_writable_writablefinished
[`zlib.createDeflate()`]: zlib.html#zlib_zlib_createdeflate_options
[API for stream consumers]: #stream_api_for_stream_consumers
[API for stream implementers]: #stream_api_for_stream_implementers
[Compatibility]: #stream_compatibility_with_older_node_js_versions
[HTTP requests, on the client]: http.html#http_class_http_clientrequest
[HTTP responses, on the server]: http.html#http_class_http_serverresponse
[TCP sockets]: net.html#net_class_net_socket
[child process stdin]: child_process.html#child_process_subprocess_stdin
[child process stdout and stderr]: child_process.html#child_process_subprocess_stdout
[crypto]: crypto.html
[fs read streams]: fs.html#fs_class_fs_readstream
[fs write streams]: fs.html#fs_class_fs_writestream
[http-incoming-message]: http.html#http_class_http_incomingmessage
[hwm-gotcha]: #stream_highwatermark_discrepancy_after_calling_readable_setencoding
[object-mode]: #stream_object_mode
[readable-_construct]: #stream_readable_construct_callback
[readable-_destroy]: #stream_readable_destroy_err_callback
[readable-destroy]: #stream_readable_destroy_error
[stream-_final]: #stream_writable_final_callback
[stream-_flush]: #stream_transform_flush_callback
[stream-_read]: #stream_readable_read_size_1
[stream-_transform]: #stream_transform_transform_chunk_encoding_callback
[stream-_write]: #stream_writable_write_chunk_encoding_callback_1
[stream-_writev]: #stream_writable_writev_chunks_callback
[stream-end]: #stream_writable_end_chunk_encoding_callback
[stream-pause]: #stream_readable_pause
[stream-push]: #stream_readable_push_chunk_encoding
[stream-read]: #stream_readable_read_size
[stream-resume]: #stream_readable_resume
[stream-uncork]: #stream_writable_uncork
[stream-write]: #stream_writable_write_chunk_encoding_callback
[Three states]: #stream_three_states
[writable-_construct]: #stream_writable_construct_callback
[writable-_destroy]: #stream_writable_destroy_err_callback
[writable-destroy]: #stream_writable_destroy_error
[writable-new]: #stream_new_stream_writable_options
[zlib]: zlib.html