當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Node.js readable.push(chunk[, encoding])用法及代碼示例

readable.push(chunk[, encoding])

曆史
版本變化
v8.0.0

chunk 參數現在可以是 Uint8Array 實例。


參數
  • chunk <Buffer> | <Uint8Array> | <string> | <null> | <any> 要推入讀取隊列的數據塊。對於不在對象模式下運行的流,chunk 必須是字符串,BufferUint8Array。對於對象模式流,chunk 可以是任何 JavaScript 值。
  • encoding <string> 字符串塊的編碼。必須是有效的 Buffer 編碼,例如 'utf8''ascii'
  • 返回: <boolean> true 如果可以繼續推送額外的數據塊; false 否則。

chunkBufferUint8Arraystring 時,將把 chunk 的數據添加到內部隊列中,供流的用戶使用。將 chunk 作為 null 傳遞表示流結束 (EOF),之後無法寫入更多數據。

Readable在暫停模式下運行時,在 'readable' 事件觸發時,可以通過調用 readable.read() 方法讀出添加readable.push()的數據。

Readable 在流動模式下運行時,添加了readable.push() 的數據將通過發出'data' 事件來傳遞。

readable.push() 方法旨在盡可能靈活。例如,當包裝提供某種形式的暫停/恢複機製和數據回調的 lower-level 源時,低級源可以由自定義 Readable 實例包裝:

// `_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() 方法驅動。

對於未在對象模式下運行的流,如果 readable.push()chunk 參數為 undefined ,它將被視為空字符串或緩衝區。有關詳細信息,請參閱 readable.push('')

相關用法


注:本文由純淨天空篩選整理自nodejs.org大神的英文原創作品 readable.push(chunk[, encoding])。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。