Stream : Abstract interface for streaming data
A stream is an abstract interface for working with streaming data. The stream
module provides an API for implementing the stream interface.
Streams can be readable, writable, or both. All streams are instances of EventEmitter
.
To access the stream
module:
const stream = require('stream');
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.
Types Of Streams
There are four fundamental stream types within JSRE
:
Writable
: streams to which data can be written.Readable
: streams from which data can be read.Duplex
: streams that are bothReadable
andWritable
.Transform
: Duplex streams that can modify or transform the data as it is written and read.
Object Mode
All streams created by JSRE
APIs operate exclusively on strings and Buffer 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
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. 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)
. If the consumer of the Stream does not call 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)
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
stream 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
Writable
streams 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
stream 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.
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:
const myStream = getWritableStreamSomehow();
myStream.write('some data');
myStream.write('some more data');
myStream.end('done writing data');
Readable Streams
Readable streams are an abstraction for a source from which data is consumed.
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. 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()
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()
method. - Calling the
stream.pipe()
method to send the data to aWritable
.
The Readable
can switch back to paused mode using one of the following:
- If there are no pipe destinations, by calling the
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()
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.
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
.
While readable.readableFlowing
is false
, data may be accumulating within the stream's internal buffer.
Choose One API Style
The Readable
stream API 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()
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.
Duplex Streams
Duplex streams are streams that implement both the Readable
and Writable
interfaces.
Support
The following shows stream
module APIs available for each permissions.
User Mode | Privilege Mode | |
---|---|---|
Writable | ● | ● |
writable.destroy | ● | ● |
writable.end | ● | ● |
writable.write | ● | ● |
writable.setDefaultEncoding | ● | ● |
writable.destroyed | ● | ● |
writable.writable | ● | ● |
writable.writableEnded | ● | ● |
writable.writableFinished | ● | ● |
writable.writableHighWaterMark | ● | ● |
writable.writableLength | ● | ● |
writable.writableNeedDrain | ● | ● |
writable.writableObjectMode | ● | ● |
writable._write | ● | ● |
writable._destroy | ● | ● |
writable._final | ● | ● |
Readable | ● | ● |
readable.destroy | ● | ● |
readable.isPaused | ● | ● |
readable.pause | ● | ● |
readable.pipe | ● | ● |
readable.read | ● | ● |
readable.resume | ● | ● |
readable.setEncoding | ● | ● |
readable.unpipe | ● | ● |
readable.destroyed | ● | ● |
readable.readable | ● | ● |
readable.readableEncoding | ● | ● |
readable.readableEnded | ● | ● |
readable.readableFlowing | ● | ● |
readable.readableHighWaterMark | ● | ● |
readable.readableLength | ● | ● |
readable.readableObjectMode | ● | ● |
readable._read | ● | ● |
readable._destroy | ● | ● |
readable.push | ● | ● |
Duplex | ● | ● |
Transform | ● | ● |
Throttle | ● | ● |
Writable Object
writable.destroy([error])
error
{Error} Optional, an error to emit with'error'
event.- Returns: Self object.
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 error. This is a destructive and immediate way to destroy a stream. 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.end([chunk[, encoding]][, callback])
chunk
{String | Buffer | Any} Optional data to write. For streams not operating in object mode, chunk must be astring
orBuffer
. For object mode streams, chunk may be any JavaScript value other thannull
.encoding
{String} The encoding, if chunk is a string. default: 'utf8'.callback
{Function} Optional callback for when the stream finishes or errorserror
{Error} Error object.
- Returns: Self object.
Calling the writable.end()
method signals that no more data will be written to the Writable
. The optional chunk
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()
method after calling stream.end()
will raise an error.
Example
// 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.write(chunk[, encoding][, callback])
chunk
{String | Buffer | Any} Optional data to write. For streams not operating in object mode, chunk must be astring
orBuffer
. For object mode streams, chunk may be any JavaScript value other than null.encoding
{String} The encoding, if chunk is a string. default: 'utf8'. A Writable stream in object mode will always ignore the encoding argument.callback
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; otherwisetrue
.
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, Writable will buffer all written chunks until buffer more then the alertWaterMark
configured, at which point it will emit 'error'
event if autoAlert
configured to true
.
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:
function write(data, cb) {
if (!stream.write(data)) {
stream.once('drain', cb);
} else {
Task.nextTick(cb);
}
}
// Wait for cb to be called before doing any other write.
write('hello', () => {
console.log('Write completed, do more writes now.');
});
writable.setDefaultEncoding(encoding)
encoding
{String} The new default encoding. The valid encoding can be: 'utf8', 'utf-8', 'hex', 'base64', 'ascii'.- Returns: {Writable} This.
The writable.setDefaultEncoding()
method sets the default encoding for a Writable
stream.
writable.destroyed
- {Boolean} Is
true
afterwritable.destroy()
has been called.
writable.writable
- {Boolean} Is
true
if it is safe to callwritable.write()
, which means the stream has not been destroyed, errored or ended.
writable.writableEnded
- {Boolean} Is
true
afterwritable.end()
has been called. This property does not indicate whether the data has been flushed, for this usewritable.writableFinished
instead.
writable.writableFinished
- {Boolean} Is set to
true
immediately before the'finish'
event is emitted.
writable.writableHighWaterMark
- {Integer} Return the value of
highWaterMark
passed when constructing thisWritable
.
writable.writableLength
- {Integer} This property contains the number of bytes in the queue ready to be written. The value provides introspection data regarding the status of the
highWaterMark
.
writable.writableNeedDrain
- {Boolean} Is true if the stream's buffer has been full and stream will emit
drain
.
writable.writableObjectMode
- {Boolean} Getter for the property
objectMode
of a givenWritable
stream.
Writable Events
close
The 'close'
event is emitted when the stream and any of its underlying resources (a file descriptor, for example) have been closed. The event indicates that no more events will be emitted, and no further computation will occur.
A Writable
stream will always emit the 'close'
event if it is created with the emitClose
option.
drain
If a call to stream.write(chunk)
returns false
, the 'drain'
event will be emitted when it is appropriate to resume writing data to the stream.
Example
// Write the data to the supplied writable stream one million times.
// Be attentive to back-pressure.
function writeOneMillionTimes(writer, data, callback) {
let i = 1000000;
write();
function write() {
let ok = true;
do {
i--;
if (i === 0) {
// Last time!
writer.write(data, callback);
} else {
// See if we should continue, or wait.
// Don't pass the callback, because we're not done yet.
ok = writer.write(data);
}
} while (i > 0 && ok);
if (i > 0) {
// Had to stop early!
// Write some more once it drains.
writer.once('drain', write);
}
}
}
error
- {Error} The
'error'
event is emitted if an error occurred while writing or piping data. The listener callback is passed a singleError
argument when called.
The stream is closed when the 'error'
event is emitted unless the autoDestroy
option was set to false
when creating the stream.
After 'error'
, no further events other than 'close'
should be emitted (including 'error'
events).
finish
The 'finish'
event is emitted after the stream.end()
method has been called, and all data has been flushed to the underlying system.
Example
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');
pipe
src
{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.
Example
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);
unpipe
src
{Readable} The source stream that unpiped this writable.
The 'unpipe'
event is emitted when the stream.unpipe()
method is called on a Readable
stream, removing this Writable
from its set of destinations.
This is also emitted in case this Writable
stream emits an error when a Readable
stream pipes into it.
Example
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 API Implementers
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()
method.
new stream.Writable([options])
options
{Object}highWaterMark
{Integer} Buffer level whenstream.write()
starts returningfalse
. default: 16KB or 16 forobjectMode
streams.decodeStrings
{Boolean} Whether to encode strings passed tostream.write()
toBuffers
(with the encoding specified in thestream.write()
call) before passing them tostream._write()
. Other types of data are not converted (i.e.Buffers
are not decoded into strings). Setting tofalse
will prevent strings from being converted. default:true
.defaultEncoding
{String} The default encoding that is used when no encoding is specified as an argument tostream.write()
. The valid encoding can be: 'utf8', 'utf-8', 'hex', 'base64', 'ascii'. default: 'utf8'.emitClose
{Boolean} Whether or not the stream should emit'close'
after it has been destroyed. default:true
.autoDestroy
{Boolean} Whether this stream should automatically call.destroy()
on itself after ending. default:true
.alertWaterMark
{Integer} JSRE expansion, when stream buffer size exceeds thealertWaterMark
, the writing data will be ignored,alertWaterMark
must bigger thanhighWaterMark
. default: Infinity - not ingored data forever.autoAlert
{Boolean} JSRE expansion, default: true - emiterror
when buf size reachalertWaterMark
otherwise ignore.objectMode
{Boolean} Whether or not thestream.write(anyObj)
is a valid operation. When set, it becomes possible to write JavaScript values other thanstring
,Buffer
if supported by the stream implementation. default: false.construct
{Function} Implementation for thestream._construct()
method.write
{Function} Implementation for thestream._write()
method.destroy
{Function} Implementation for thestream._destroy()
method.final
{Function} Implementation for thestream._final()
method.
Example
const { Writable } = require('stream');
class MyWritable extends Writable {
constructor(options) {
// Calls the stream.Writable() constructor.
super(options);
// ...
}
}
Or, when using pre-ES6 style constructors:
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:
const { Writable } = require('stream');
const myWritable = new Writable({
write(chunk, callback) {
// ...
},
});
writable._construct(callback)
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.
Example
const { Writable } = require('stream');
const fs = require('fs');
class WriteStream extends Writable {
constructor(filename) {
super();
this.filename = filename;
this.file = undefined;
}
_construct(callback) {
var file = fs.open(this.filename, 'w', 0o666);
if (!file) {
callback(new Error('Open file fail.'));
} else {
this.file = file;
callback();
}
}
_write(chunk, encoding, callback) {
try {
var size = this.file.write(chunk);
callback(null, size);
} catch(e) {
callback(e);
}
}
_destroy(err, callback) {
if (this.file) {
this.file.close();
this.file = undefined;
callback(err);
} else {
callback(err);
}
}
}
writable._write(chunk, encoding, callback)
chunk
{String | Buffer | Any} TheBuffer
to be written, converted from the string passed tostream.write()
. If the stream'sdecodeStrings
option isfalse
or the stream is operating in object mode, the chunk will not be converted & will be whatever was passed tostream.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
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()
method to send data to the underlying resource.
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.
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._destroy(err, callback)
err
{Error} A possible error.callback
{Function} A callback function that takes an optional error argument.error
{Error} Error object.
The _destroy()
method is called by writable.destroy()
. It can be overridden by child classes but it must not be called directly.
writable._final(callback)
callback
{Function} Call this function (optionally with an error argument) when finished writing any remaining data.error
{Error} Error object.
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()
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.
Example
const { Writable } = require('stream');
const myWritable = new Writable({
write(chunk, 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:
const { Writable } = require('stream');
class MyWritable extends Writable {
_write(chunk, callback) {
if (chunk.toString().indexOf('a') >= 0) {
callback(new Error('chunk is invalid'));
} else {
callback();
}
}
}
Readable Object
readable.destroy([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.isPaused()
- Returns: {Boolean} Stream paused or not.
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.
Example
const readable = new stream.Readable();
readable.isPaused(); // === false
readable.pause();
readable.isPaused(); // === true
readable.resume();
readable.isPaused(); // === false
readable.pause()
- Returns: this.
The readable.pause()
method will cause a stream in flowing mode to stop emitting 'data'
events, switching out of flowing mode. Any data that becomes available will remain in the internal buffer.
Example
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);
});
readable.pipe(destination[, options])
destination
{Writable} The destination for writing data.options
{Object} Pipe options:end
{Boolean} End the writer when the reader ends. default:true
.
- Returns: {Writable} The destination, allowing for a chain of pipes if it is a
Duplex
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
:
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);
By default, 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:
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.
readable.read([size])
size
{Integer} Optional argument to specify how much data to read.- Returns: {Buffer | String | null} Read data.
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. If encoding is 'utf8' and a byte sequence in read buffer is not valid UTF-8
, then the character \uFFFD
will be returns.
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.
If the size
argument is not specified, all of the data contained in the internal buffer will be returned.
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.
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)
, 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\])
after the 'end'
event has been emitted will return null
. No runtime error will be raised.
readable.resume()
- Returns: this.
The readable.resume()
method causes an explicitly paused Readable
stream to resume emitting 'data'
events, switching the stream into flowing mode.
The readable.resume()
method can be used to fully consume the data from a stream without actually processing any of that data:
getReadableStreamSomehow()
.resume()
.on('end', () => {
console.log('Reached the end, but did not read anything.');
});
readable.setEncoding(encoding)
encoding
{String} The encoding to use.- Returns: {Readable} This object.
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.
Example
const read = () => { readAble.push('hello') };
const readAble = new Readable({ read });
readAble.setEncoding('hex');
readAble.on('data', (str) => {
console.log(str);
});
readable.unpipe([destination])
destination
{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.
Example
const fs = require('stream').FsReadStream;
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.destroyed
- {Boolean} Is
true
afterreadable.destroy()
has been called.
readable.readable
- {Boolean} Is
true
if it is safe to callreadable.read()
, which means the stream has not been destroyed or emitted'error'
or'end'
.
readable.readableEncoding
- {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
- {Boolean} Becomes
true
when'end'
event is emitted.
readable.readableFlowing
- {Boolean} This property reflects the current state of a
Readable
stream as described in the Stream Three States section.
readable.readableHighWaterMark
- {Integer} Returns the value of
highWaterMark
passed when constructing thisReadable
.
readable.readableLength
- {Integer} This property contains the number of bytes in the queue ready to be read. The value provides introspection data regarding the status of the
highWaterMark
.
readable.readableObjectMode
- {Boolean} Getter for the property
objectMode
of a givenReadable
stream.
Readable Events
close
The 'close'
event is emitted when the stream and any of its underlying resources (a file descriptor, for example) have been closed. The event indicates that no more events will be emitted, and no further computation will occur.
A Readable
stream will always emit the 'close'
event if it is created with the emitClose
option.
data
chunk
{Buffer | String} The chunk of data. For streams that are not operating in object mode, the chunk will be either a string orBuffer
. 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
. If the stream using the readable.setEncoding()
method set stream encoding, the character \uFFFD
will be returns while a byte sequence in read buffer is not valid encoding.
Example
const readable = getReadableStreamSomehow();
readable.on('data', (chunk) => {
console.log(`Received ${chunk.length} bytes of data.`);
});
end
The 'end'
event is emitted when there is no more data to be consumed from the stream.
The 'end'
event will not be emitted unless the data is completely consumed. This can be accomplished by switching the stream into flowing mode, or by calling stream.read()
repeatedly until all data has been consumed.
Example
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.');
});
error
err
{Error} Error object.
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.
pause
The 'pause'
event is emitted when stream.pause()
is called and readableFlowing
is not false
.
readable
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.
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()
will return the available data. In the latter case, stream.read()
will return null
. For instance, in the following example, foo.txt
is an empty file:
const fs = require('stream').FsReadStream;
const rr = fs.createReadStream('foo.txt');
rr.on('readable', () => {
console.log(`readable: ${rr.read()}`);
});
rr.on('end', () => {
console.log('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()
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()
.
resume
The 'resume'
event is emitted when stream.resume()
is called and readableFlowing
is not true
.
Readable API Implementers
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])
options
highWaterMark
{Integer} The maximum number of bytes to store in the internal buffer before ceasing to read from the underlying resource. default: 16KB or 16 forobjectMode
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) returns a single value instead of aBuffer
of size n. default:false
.emitClose
{Boolean} Whether or not the stream should emit'close'
after it has been destroyed. default:true
.autoDestroy
{Boolean} Whether this stream should automatically call.destroy()
on itself after ending. default:true
.alertWaterMark
{Integer} JSRE expansion, when stream buffer size exceeds the 'alertWaterMark', the underlying reading data will be ignored, 'alertWaterMark' must bigger than 'highWaterMark'. default: Infinity - not ingored data forever.autoAlert
{Boolean} JSRE expansion, default: true - emiterror
when buf size reachalertWaterMark
otherwise ignore.construct
{Function} Implementation for thestream._construct()
method.read
{Function} Implementation for thestream._read()
method.destroy
{Function} Implementation for thestream._destroy()
method.
Example
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:
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:
const { Readable } = require('stream');
const myReadable = new Readable({
read(size) {
// ...
}
});
readable._construct(callback)
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.
Example
const { Readable } = require('stream');
const fs = require('fs');
class ReadStream extends Readable {
constructor(filename) {
super();
this.filename = filename;
this.file = undefined;
}
_construct(callback) {
var file = fs.open(this.filename, 'r', 0o666);
if (!file) {
callback(new Error('Open file fail.'));
} else {
this.file = file;
callback();
}
}
_read(n) {
try {
var buf = new Buffer(n);
var num = this.file.read(buf, 0, n);
this.push(num > 0 ? buf.slice(0, num) : null);
} catch(e) {
this.destroy(e);
}
}
_destroy(err, callback) {
if (this.file) {
this.file.close();
this.file = undefined;
callback(err);
} else {
callback(err);
}
}
}
readable._read([size])
size
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)
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()
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)
.
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)
err
{Error} A possible error.callback
{Function} A callback function that takes an optional error argument.error
{Error} Error object.
The _destroy()
method is called by readable.destroy()
. It can be overridden by child classes but it must not be called directly.
readable.push(chunk[, encoding])
chunk
{Buffer | String | null | Any} Chunk of data to push into the read queue. For streams not operating in object mode, chunk must be a string orBuffer
. For object mode streams, chunk may be any JavaScript value.encoding
{String} Encoding of string chunks. Must be a validBuffer
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
,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()
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:
// `_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)
method. Throwing an Error
from within readable._read()
or manually emitting an 'error'
event results in undefined behavior.
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
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.
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);
this.push(buf);
}
}
}
Duplex API Implementers
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
andstream.Writable
classes).
The stream.Duplex
class prototypically inherits from stream.Readable
and parasitically from 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)
options
{Object} Passed to bothWritable
andReadable
constructors. Also has the following fields:allowHalfOpen
{Boolean} If set tofalse
, then the stream will automatically end the writable side when the readable side ends. default:true
.readableObjectMode
{Boolean} SetsobjectMode
for readable side of the stream. Has no effect ifobjectMode
is true. default:false
.writableObjectMode
{Boolean} SetsobjectMode
for writable side of the stream. Has no effect ifobjectMode
is true. default:false
.readableHighWaterMark
{Integer} SetshighWaterMark
for the readable side of the stream. Has no effect ifhighWaterMark
is provided.writableHighWaterMark
{Integer} SetshighWaterMark
for the writable side of the stream. Has no effect ifhighWaterMark
is provided.
Example
const { Duplex } = require('stream');
class MyDuplex extends Duplex {
constructor(options) {
super(options);
// ...
}
}
Or, when using pre-ES6 style constructors:
const { Duplex } = require('stream');
const util = require('util');
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:
const { Duplex } = require('stream');
const myDuplex = new Duplex({
read(size) {
// ...
},
write(chunk, encoding, callback) {
// ...
}
});
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. 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.
const { Duplex } = require('stream');
const kSource = Symbol('source');
class MyDuplex extends Duplex {
constructor(source, options) {
super(options);
this[kSource] = source;
}
_write(chunk, encode, callback) {
if (!Buffer.isBuffer(chunk)) {
encode = encode || 'utf-8';
chunk = Buffer.from(chunk, encode);
}
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.
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.
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
Transform API Implementers
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()
method and may also implement the transform._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 bothWritable
andReadable
constructors. Also has the following fields:transform
{Function} Implementation for the stream._transform() method.flush
{Function} Implementation for the stream._flush() method.
Example
const { Transform } = require('stream');
class MyTransform extends Transform {
constructor(options) {
super(options);
// ...
}
}
Or, when using pre-ES6 style constructors:
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:
const { Transform } = require('stream');
const myTransform = new Transform({
transform(chunk, encoding, callback) {
// ...
}
});
transform._flush(callback)
callback
{Function} A callback function (optionally with an error argument and data) to be called when remaining data has been flushed.error
{Error} Error object.chunk
{Buffer | String | null} Data to be written if exist.
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 transform.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 tostream.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 tostream.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 valuebuffer
. 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.error
{Error} Error object.chunk
{Buffer | String | null} Data to be written if exist.
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 transform.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 transform.push()
method. In other words, the following are equivalent:
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.
Throttle Readable Class
Throttle is a special Readable
class suitable for reading current limit, which can be used to limit the rate of Readable
.
new Throttle(src[, opts[, streamOpts]])
src
{Readable} SourceReadable
stream object.opts
{Object} Options.rate
{Integer} Read rate: Number of bytes read per second.
streamOpts
{Object} Options for creating thisReadable
Stream.- Returns: {Readable} Throttle readable object.
Create a Readable
stream object that limits the read rate.
// Create a stream that reads the specified file
var src = fs.createReadStream('./data.txt');
// Create a stream with a read rate of 50 KBytes/s
var thr = new Throttle(src, { rate: 50 * 1024 });
// Start time
var start = Date.now();
// Read data from throttle readable stream
thr.on('data', () => {});
thr.on('end', () => {
var cost = Date.now() - start;
console.log('cost:', cost, 'ms');
});
Use this object to limit network access traffic, etc. This class is available in EdgerOS 1.9.8 and later.
Throttle Readable Object
throttle.rate
- {Integer} Read rate: Number of bytes read per second.
throttle.rate
is a getter
and setter
, used to get and set read rate, users can dynamically set this parameter.
// Create a stream with a read rate ability
var thr = new Throttle(src);
// Set read rate 128 KBytes/s
thr.rate = 128 * 1024;