readable.push(chunk[, encoding])
chunk<Buffer> | <TypedArray> | <DataView> | <string> | <null> | <any> 要推送到读取队列的数据块。对于非对象模式的流,chunk必须是 <string>、<Buffer>、<TypedArray> 或 <DataView>。对于对象模式的流,chunk可以是任何 JavaScript 值。encoding<string> 字符串块的编码。必须是有效的Buffer编码,例如'utf8'或'ascii'。- 返回:<boolean> 如果可以继续推送更多数据块,返回
true;否则返回false。
当 chunk 是 <Buffer>、<TypedArray>、<DataView> 或 <string> 时,该数据 chunk 将被添加到内部队列中供流的用户使用。将 chunk 传递为 null 表示流的结束 (EOF),此后无法再写入更多数据。
【When chunk is a <Buffer>, <TypedArray>, <DataView> 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.】
当 Readable 处于暂停模式时,通过 readable.push() 添加的数据可以在 'readable' 事件触发时,通过调用 readable.read() 方法读取出来。
【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.】
当 Readable 在流动模式下运行时,通过 readable.push() 添加的数据将通过触发 'data' 事件来传递。
【When the Readable is operating in flowing mode, the data added with
readable.push() will be delivered by emitting a 'data' event.】
readable.push() 方法的设计尽可能灵活。例如,在封装提供某种暂停/恢复机制和数据回调的低级源时,可以使用自定义 Readable 实例来封装低级源:
【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();
}
} readable.push() 方法用于将内容推入内部缓冲区。它可以由 readable._read() 方法驱动。
【The readable.push() method is used to push the content
into the internal buffer. It can be driven by the readable._read() method.】
对于不在对象模式下运行的流,如果 readable.push() 的 chunk 参数为 undefined,它将被视为空字符串或缓冲区。更多信息请参见 readable.push('')。
【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.】