{ "source": "doc/api/stream.markdown", "modules": [ { "textRaw": "Stream", "name": "stream", "stability": 2, "stabilityText": "Unstable", "desc": "
A stream is an abstract interface implemented by various objects in\nNode. For example a request to an HTTP server is a stream, as is\nstdout. Streams are readable, writable, or both. All streams are\ninstances of [EventEmitter][]\n\n
\nYou can load the Stream base classes by doing require('stream')
.\nThere are base classes provided for Readable streams, Writable\nstreams, Duplex streams, and Transform streams.\n\n
In earlier versions of Node, the Readable stream interface was\nsimpler, but also less powerful and less useful.\n\n
\nread()
method, 'data'
\nevents would start emitting immediately. If you needed to do some\nI/O to decide how to handle data, then you had to store the chunks\nin some kind of buffer so that they would not be lost.pause()
method was advisory, rather than guaranteed. This\nmeant that you still had to be prepared to receive 'data'
events\neven when the stream was in a paused state.In Node v0.10, the Readable class described below was added. For\nbackwards compatibility with older Node programs, Readable streams\nswitch into "old mode" when a 'data'
event handler is added, or when\nthe pause()
or resume()
methods are called. The effect is that,\neven if you are not using the new read()
method and 'readable'
\nevent, you no longer have to worry about losing 'data'
chunks.\n\n
Most programs will continue to function normally. However, this\nintroduces an edge case in the following conditions:\n\n
\n'data'
event handler is added.pause()
and resume()
methods are never called.For example, consider the following code:\n\n
\n// WARNING! BROKEN!\nnet.createServer(function(socket) {\n\n // we add an 'end' method, but never consume the data\n socket.on('end', function() {\n // It will never get here.\n socket.end('I got your message (but didnt read it)\\n');\n });\n\n}).listen(1337);
\nIn versions of node prior to v0.10, the incoming message data would be\nsimply discarded. However, in Node v0.10 and beyond, the socket will\nremain paused forever.\n\n
\nThe workaround in this situation is to call the resume()
method to\ntrigger "old mode" behavior:\n\n
// Workaround\nnet.createServer(function(socket) {\n\n socket.on('end', function() {\n socket.end('I got your message (but didnt read it)\\n');\n });\n\n // start the flow of data, discarding it.\n socket.resume();\n\n}).listen(1337);
\nIn addition to new Readable streams switching into old-mode, pre-v0.10\nstyle streams can be wrapped in a Readable class using the wrap()
\nmethod.\n\n
A Readable Stream
has the following methods, members, and events.\n\n
Note that stream.Readable
is an abstract class designed to be\nextended with an underlying implementation of the _read(size, cb)
\nmethod. (See below.)\n\n
In classes that extend the Readable class, make sure to call the\nconstructor so that the buffering settings can be properly\ninitialized.\n\n
\n" }, { "textRaw": "readable.\\_read(size, callback)", "type": "method", "name": "\\_read", "signatures": [ { "params": [ { "textRaw": "`size` {Number} Number of bytes to read asynchronously ", "name": "size", "type": "Number", "desc": "Number of bytes to read asynchronously" }, { "textRaw": "`callback` {Function} Called with an error or with data ", "name": "callback", "type": "Function", "desc": "Called with an error or with data" } ] }, { "params": [ { "name": "size" }, { "name": "callback" } ] } ], "desc": "All Readable stream implementations must provide a _read
method\nto fetch data from the underlying resource.\n\n
Note: This function MUST NOT be called directly. It should be\nimplemented by child classes, and called by the internal Readable\nclass methods only.\n\n
\nCall the callback using the standard callback(error, data)
pattern.\nWhen no more data can be fetched, call callback(null, null)
to\nsignal the EOF.\n\n
This method is prefixed with an underscore because it is internal to\nthe class that defines it, and should not be called directly by user\nprograms. However, you are expected to override this method in\nyour own extension classes.\n\n
\n" }, { "textRaw": "readable.push(chunk)", "type": "method", "name": "push", "signatures": [ { "return": { "textRaw": "return {Boolean} Whether or not more pushes should be performed ", "name": "return", "type": "Boolean", "desc": "Whether or not more pushes should be performed" }, "params": [ { "textRaw": "`chunk` {Buffer | null | String} Chunk of data to push into the read queue ", "name": "chunk", "type": "Buffer | null | String", "desc": "Chunk of data to push into the read queue" } ] }, { "params": [ { "name": "chunk" } ] } ], "desc": "The Readable
class works by putting data into a read queue to be\npulled out later by calling the read()
method when the 'readable'
\nevent fires.\n\n
The push()
method will explicitly insert some data into the read\nqueue. If it is called with null
then it will signal the end of the\ndata.\n\n
In some cases, you may be wrapping a lower-level source which has some\nsort of pause/resume mechanism, and a data callback. In those cases,\nyou could wrap the low-level source object by doing something like\nthis:\n\n
\n// source is an object with readStop() and readStart() methods,\n// and an `ondata` member that gets called when it has data, and\n// an `onend` member that gets called when the data is over.\n\nvar stream = new Readable();\n\nsource.ondata = function(chunk) {\n // if push() returns false, then we need to stop reading from source\n if (!stream.push(chunk))\n source.readStop();\n};\n\nsource.onend = function() {\n stream.push(null);\n};\n\n// _read will be called when the stream wants to pull more data in\nstream._read = function(size, cb) {\n source.readStart();\n};
\n"
},
{
"textRaw": "readable.wrap(stream)",
"type": "method",
"name": "wrap",
"signatures": [
{
"params": [
{
"textRaw": "`stream` {Stream} An \"old style\" readable stream ",
"name": "stream",
"type": "Stream",
"desc": "An \"old style\" readable stream"
}
]
},
{
"params": [
{
"name": "stream"
}
]
}
],
"desc": "If you are using an older Node library that emits 'data'
events and\nhas a pause()
method that is advisory only, then you can use the\nwrap()
method to create a Readable stream that uses the old stream\nas its data source.\n\n
For example:\n\n
\nvar OldReader = require('./old-api-module.js').OldReader;\nvar oreader = new OldReader;\nvar Readable = require('stream').Readable;\nvar myReader = new Readable().wrap(oreader);\n\nmyReader.on('readable', function() {\n myReader.read(); // etc.\n});
\n"
},
{
"textRaw": "readable.setEncoding(encoding)",
"type": "method",
"name": "setEncoding",
"desc": "Makes the 'data'
event emit a string instead of a Buffer
. encoding
\ncan be 'utf8'
, 'utf16le'
('ucs2'
), 'ascii'
, or 'hex'
.\n\n
The encoding can also be set by specifying an encoding
field to the\nconstructor.\n\n
Call this method to consume data once the 'readable'
event is\nemitted.\n\n
The size
argument will set a minimum number of bytes that you are\ninterested in. If not set, then the entire content of the internal\nbuffer is returned.\n\n
If there is no data to consume, or if there are fewer bytes in the\ninternal buffer than the size
argument, then null
is returned, and\na future 'readable'
event will be emitted when more is available.\n\n
Note that calling stream.read(0)
will always return null
, and will\ntrigger a refresh of the internal buffer, but otherwise be a no-op.\n\n
Connects this readable stream to destination
WriteStream. Incoming\ndata on this stream gets written to destination
. Properly manages\nback-pressure so that a slow destination will not be overwhelmed by a\nfast readable stream.\n\n
This function returns the destination
stream.\n\n
For example, emulating the Unix cat
command:\n\n
process.stdin.pipe(process.stdout);
\nBy default end()
is called on the destination when the source stream\nemits end
, so that destination
is no longer writable. Pass { end:\nfalse }
as options
to keep the destination stream open.\n\n
This keeps writer
open so that "Goodbye" can be written at the\nend.\n\n
reader.pipe(writer, { end: false });\nreader.on("end", function() {\n writer.end("Goodbye\\n");\n});
\nNote that process.stderr
and process.stdout
are never closed until\nthe process exits, regardless of the specified options.\n\n
Undo a previously established pipe()
. If no destination is\nprovided, then all previously established pipes are removed.\n\n
Switches the readable stream into "old mode", where data is emitted\nusing a 'data'
event rather than being buffered for consumption via\nthe read()
method.\n\n
Ceases the flow of data. No 'data'
events are emitted while the\nstream is in a paused state.\n\n
Switches the readable stream into "old mode", where data is emitted\nusing a 'data'
event rather than being buffered for consumption via\nthe read()
method.\n\n
Resumes the incoming 'data'
events after a pause()
.\n\n\n
When there is data ready to be consumed, this event will fire. The\nnumber of bytes that are required to be considered "readable" depends\non the lowWaterMark
option set in the constructor.\n\n
When this event emits, call the read()
method to consume the data.\n\n
Emitted when the stream has received an EOF (FIN in TCP terminology).\nIndicates that no more 'data'
events will happen. If the stream is\nalso writable, it may be possible to continue writing.\n\n
The 'data'
event emits either a Buffer
(by default) or a string if\nsetEncoding()
was used.\n\n
Note that adding a 'data'
event listener will switch the Readable\nstream into "old mode", where data is emitted as soon as it is\navailable, rather than waiting for you to call read()
to consume it.\n\n
Emitted if there was an error receiving data.\n\n
\n", "params": [] }, { "textRaw": "Event: 'close'", "type": "event", "name": "close", "desc": "Emitted when the underlying resource (for example, the backing file\ndescriptor) has been closed. Not all streams will emit this.\n\n
\n", "params": [] } ] }, { "textRaw": "Class: stream.Writable", "type": "class", "name": "stream.Writable", "desc": "A Writable
Stream has the following methods, members, and events.\n\n
Note that stream.Writable
is an abstract class designed to be\nextended with an underlying implementation of the _write(chunk, cb)
\nmethod. (See below.)\n\n
In classes that extend the Writable class, make sure to call the\nconstructor so that the buffering settings can be properly\ninitialized.\n\n
\n" }, { "textRaw": "writable.\\_write(chunk, callback)", "type": "method", "name": "\\_write", "signatures": [ { "params": [ { "textRaw": "`chunk` {Buffer | Array} The data to be written ", "name": "chunk", "type": "Buffer | Array", "desc": "The data to be written" }, { "textRaw": "`callback` {Function} Called with an error, or null when finished ", "name": "callback", "type": "Function", "desc": "Called with an error, or null when finished" } ] }, { "params": [ { "name": "chunk" }, { "name": "callback" } ] } ], "desc": "All Writable stream implementations must provide a _write
method to\nsend data to the underlying resource.\n\n
Note: This function MUST NOT be called directly. It should be\nimplemented by child classes, and called by the internal Writable\nclass methods only.\n\n
\nCall the callback using the standard callback(error)
pattern to\nsignal that the write completed successfully or with an error.\n\n
If the decodeStrings
flag is set in the constructor options, then\nchunk
will be an array rather than a Buffer. This is to support\nimplementations that have an optimized handling for certain string\ndata encodings.\n\n
This method is prefixed with an underscore because it is internal to\nthe class that defines it, and should not be called directly by user\nprograms. However, you are expected to override this method in\nyour own extension classes.\n\n\n
\n" }, { "textRaw": "writable.write(chunk, [encoding], [callback])", "type": "method", "name": "write", "signatures": [ { "return": { "textRaw": "Returns {Boolean} ", "name": "return", "type": "Boolean" }, "params": [ { "textRaw": "`chunk` {Buffer | String} Data to be written ", "name": "chunk", "type": "Buffer | String", "desc": "Data to be written" }, { "textRaw": "`encoding` {String} Optional. If `chunk` is a string, then encoding defaults to `'utf8'` ", "name": "encoding", "type": "String", "optional": true, "desc": "If `chunk` is a string, then encoding defaults to `'utf8'`" }, { "textRaw": "`callback` {Function} Optional. Called when this chunk is successfully written. ", "name": "callback", "type": "Function", "optional": true, "desc": "Called when this chunk is successfully written." } ] }, { "params": [ { "name": "chunk" }, { "name": "encoding", "optional": true }, { "name": "callback", "optional": true } ] } ], "desc": "Writes chunk
to the stream. Returns true
if the data has been\nflushed to the underlying resource. Returns false
to indicate that\nthe buffer is full, and the data will be sent out in the future. The\n'drain'
event will indicate when the buffer is empty again.\n\n
The specifics of when write()
will return false, and when a\nsubsequent 'drain'
event will be emitted, are determined by the\nhighWaterMark
and lowWaterMark
options provided to the\nconstructor.\n\n
Call this method to signal the end of the data being written to the\nstream.\n\n
\n" } ], "events": [ { "textRaw": "Event: 'drain'", "type": "event", "name": "drain", "desc": "Emitted when the stream's write queue empties and it's safe to write\nwithout buffering again. Listen for it when stream.write()
returns\nfalse
.\n\n
Emitted when the underlying resource (for example, the backing file\ndescriptor) has been closed. Not all streams will emit this.\n\n
\n", "params": [] }, { "textRaw": "Event: 'finish'", "type": "event", "name": "finish", "desc": "When end()
is called and there are no more chunks to write, this\nevent is emitted.\n\n
Emitted when the stream is passed to a readable stream's pipe method.\n\n
\n" }, { "textRaw": "Event 'unpipe'", "type": "event", "name": "unpipe", "params": [], "desc": "Emitted when a previously established pipe()
is removed using the\nsource Readable stream's unpipe()
method.\n\n
A "duplex" stream is one that is both Readable and Writable, such as a\nTCP socket connection.\n\n
\nNote that stream.Duplex
is an abstract class designed to be\nextended with an underlying implementation of the _read(size, cb)
\nand _write(chunk, callback)
methods as you would with a Readable or\nWritable stream class.\n\n
Since JavaScript doesn't have multiple prototypal inheritance, this\nclass prototypally inherits from Readable, and then parasitically from\nWritable. It is thus up to the user to implement both the lowlevel\n_read(n,cb)
method as well as the lowlevel _write(chunk,cb)
method\non extension duplex classes.\n\n
In classes that extend the Duplex class, make sure to call the\nconstructor so that the buffering settings can be properly\ninitialized.\n\n
\n" } ] }, { "textRaw": "Class: stream.Transform", "type": "class", "name": "stream.Transform", "desc": "A "transform" stream is a duplex stream where the output is causally\nconnected in some way to the input, such as a zlib stream or a crypto\nstream.\n\n
\nThere is no requirement that the output be the same size as the input,\nthe same number of chunks, or arrive at the same time. For example, a\nHash stream will only ever have a single chunk of output which is\nprovided when the input is ended. A zlib stream will either produce\nmuch smaller or much larger than its input.\n\n
\nRather than implement the _read()
and _write()
methods, Transform\nclasses must implement the _transform()
method, and may optionally\nalso implement the _flush()
method. (See below.)\n\n
In classes that extend the Transform class, make sure to call the\nconstructor so that the buffering settings can be properly\ninitialized.\n\n
\n" }, { "textRaw": "transform.\\_transform(chunk, outputFn, callback)", "type": "method", "name": "\\_transform", "signatures": [ { "params": [ { "textRaw": "`chunk` {Buffer} The chunk to be transformed. ", "name": "chunk", "type": "Buffer", "desc": "The chunk to be transformed." }, { "textRaw": "`outputFn` {Function} Call this function with any output data to be passed to the readable interface. ", "name": "outputFn", "type": "Function", "desc": "Call this function with any output data to be passed to the readable interface." }, { "textRaw": "`callback` {Function} Call this function (optionally with an error argument) when you are done processing the supplied chunk. ", "name": "callback", "type": "Function", "desc": "Call this function (optionally with an error argument) when you are done processing the supplied chunk." } ] }, { "params": [ { "name": "chunk" }, { "name": "outputFn" }, { "name": "callback" } ] } ], "desc": "All Transform stream implementations must provide a _transform
\nmethod to accept input and produce output.\n\n
Note: This function MUST NOT be called directly. It should be\nimplemented by child classes, and called by the internal Transform\nclass methods only.\n\n
\n_transform
should do whatever has to be done in this specific\nTransform class, to handle the bytes being written, and pass them off\nto the readable portion of the interface. Do asynchronous I/O,\nprocess things, and so on.\n\n
Call the callback function only when the current chunk is completely\nconsumed. Note that this may mean that you call the outputFn
zero\nor more times, depending on how much data you want to output as a\nresult of this chunk.\n\n
This method is prefixed with an underscore because it is internal to\nthe class that defines it, and should not be called directly by user\nprograms. However, you are expected to override this method in\nyour own extension classes.\n\n
\n" }, { "textRaw": "transform.\\_flush(outputFn, callback)", "type": "method", "name": "\\_flush", "signatures": [ { "params": [ { "textRaw": "`outputFn` {Function} Call this function with any output data to be passed to the readable interface. ", "name": "outputFn", "type": "Function", "desc": "Call this function with any output data to be passed to the readable interface." }, { "textRaw": "`callback` {Function} Call this function (optionally with an error argument) when you are done flushing any remaining data. ", "name": "callback", "type": "Function", "desc": "Call this function (optionally with an error argument) when you are done flushing any remaining data." } ] }, { "params": [ { "name": "outputFn" }, { "name": "callback" } ] } ], "desc": "Note: This function MUST NOT be called directly. It MAY be implemented\nby child classes, and if so, will be called by the internal Transform\nclass methods only.\n\n
\nIn some cases, your transform operation may need to emit a bit more\ndata at the end of the stream. For example, a Zlib
compression\nstream will store up some internal state so that it can optimally\ncompress the output. At the end, however, it needs to do the best it\ncan with what is left, so that the data will be complete.\n\n
In those cases, you can implement a _flush
method, which will be\ncalled at the very end, after all the written data is consumed, but\nbefore emitting end
to signal the end of the readable side. Just\nlike with _transform
, call outputFn
zero or more times, as\nappropriate, and call callback
when the flush operation is complete.\n\n
This method is prefixed with an underscore because it is internal to\nthe class that defines it, and should not be called directly by user\nprograms. However, you are expected to override this method in\nyour own extension classes.\n\n\n
\n" } ] }, { "textRaw": "Class: stream.PassThrough", "type": "class", "name": "stream.PassThrough", "desc": "This is a trivial implementation of a Transform
stream that simply\npasses the input bytes across to the output. Its purpose is mainly\nfor examples and testing, but there are occasionally use cases where\nit can come in handy.\n\n\n