readable.pipe(destination[, options])
destination<stream.Writable> 写入数据的目标options<Object> 管道选项end<boolean> 当读取器结束时终止写入器。默认值:true。
- 返回值:<stream.Writable> destination,如果它是
Duplex或Transform流,则允许进行管道链式操作
readable.pipe() 方法将 Writable 流附加到 readable 上,使其自动切换到流动模式,并将其所有数据推送到附加的 Writable。数据的流动将被自动管理,以确保目标 Writable 流不会被速度更快的 Readable 流压垮。
【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.】
以下示例将所有来自 readable 的数据导入名为 file.txt 的文件:
【The following example pipes all of the data from the readable into a file
named 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 流。
【It is possible to attach multiple Writable streams to a single Readable
stream.】
readable.pipe() 方法返回对 destination 流的引用,从而可以建立管道流链:
【The readable.pipe() method returns a reference to the destination stream
making it possible to set up chains of piped streams:】
const fs = require('node:fs');
const zlib = require('node:zlib');
const r = fs.createReadStream('file.txt');
const z = zlib.createGzip();
const w = fs.createWriteStream('file.txt.gz');
r.pipe(z).pipe(w); 默认情况下,当源 Readable 流触发 'end' 时,stream.end() 会在目标 Writable 流上被调用,从而使目标流不再可写。要禁用此默认行为,可以将 end 选项传递为 false,使目标流保持打开状态:
【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');
}); 一个重要的注意事项是,如果 Readable 流在处理过程中发出错误,Writable 目的地 不会自动关闭。如果发生错误,需要 手动 关闭每个流,以防止内存泄漏。
【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.】
process.stderr 和 process.stdout 的 Writable 流在 Node.js 进程退出之前从不关闭,无论指定了哪些选项。
【The process.stderr and process.stdout Writable streams are never
closed until the Node.js process exits, regardless of the specified options.】