readable.pipe(destination[, options])
添加於:v0.9.4
參數
destination<stream.Writable> 寫入數據的目的地options<Object>管道選項end<boolean> 在閱讀器結束時結束編寫器。 默認:true。
- 返回:<stream.Writable> 目的地,如果它是一個管道鏈,則允許它
Duplex或一個Transform流
readable.pipe() 方法將 流附加到 Writable readable ,使其自動切換到流動模式並將其所有數據推送到附加的 。數據流將被自動管理,以便目標Writable Writable 流不會被更快的Readable 流淹沒。
以下示例將 readable 中的所有數據通過管道傳輸到名為 file.txt 的文件中:
const fs = require('node:fs');
const readable = getReadableStreamSomehow();
const writable = fs.createWriteStream('file.txt');
// All the data from readable goes into 'file.txt'.
readable.pipe(writable);
可以將多個Writable 流附加到單個Readable 流。
readable.pipe() 方法返回對目標流的引用,從而可以設置管道流鏈:
const fs = require('node:fs');
const r = fs.createReadStream('file.txt');
const z = zlib.createGzip();
const w = fs.createWriteStream('file.txt.gz');
r.pipe(z).pipe(w);
默認情況下,當源 Readable 流發出 時,在目標 'end' Writable 流上調用 ,因此目標不再可寫。要禁用此默認行為,可以將 stream.end() end 選項作為 false 傳遞,從而使目標流保持打開狀態:
reader.pipe(writer, { end: false });
reader.on('end', () => {
writer.end('Goodbye\n');
});
一個重要的警告是,如果 Readable 流在處理期間發出錯誤,則 Writable 目標不會自動關閉。如果發生錯誤,則需要手動關閉每個流以防止內存泄漏。
和 process.stderr process.stdout Writable 流在 Node.js 進程退出之前永遠不會關閉,無論指定的選項如何。
相關用法
- Node.js stream.Readable.pause()用法及代碼示例
- Node.js stream.Readable.take(limit[, options])用法及代碼示例
- Node.js stream.Readable.setEncoding(encoding)用法及代碼示例
- Node.js stream.Readable.some(fn[, options])用法及代碼示例
- Node.js stream.Readable.map(fn[, options])用法及代碼示例
- Node.js stream.Readable.toArray([options])用法及代碼示例
- Node.js stream.Readable.isPaused()用法及代碼示例
- Node.js stream.Readable.forEach(fn[, options])用法及代碼示例
- Node.js stream.Readable.every(fn[, options])用法及代碼示例
- Node.js stream.Readable.from()用法及代碼示例
- Node.js stream.Readable.read([size])用法及代碼示例
- Node.js stream.Readable.flatMap(fn[, options])用法及代碼示例
- Node.js stream.Readable.unshift(chunk[, encoding])用法及代碼示例
- Node.js stream.Readable.filter(fn[, options])用法及代碼示例
- Node.js stream.Readable.asIndexedPairs([options])用法及代碼示例
- Node.js stream.Readable.drop(limit[, options])用法及代碼示例
- Node.js stream.Readable.resume()用法及代碼示例
- Node.js stream.Readable.reduce(fn[, initial[, options]])用法及代碼示例
- Node.js stream.Readable.iterator([options])用法及代碼示例
- Node.js stream.Readable.wrap(stream)用法及代碼示例
- Node.js stream.Readable.find(fn[, options])用法及代碼示例
- Node.js stream.Readable.unpipe([destination])用法及代碼示例
- Node.js stream.Readable.from(iterable[, options])用法及代碼示例
- Node.js stream.Writable.uncork()用法及代碼示例
- Node.js stream.finished()用法及代碼示例
注:本文由純淨天空篩選整理自nodejs.org大神的英文原創作品 stream.Readable.pipe(destination[, options])。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
