readable.pipe(destination[, options])


readable.pipe() 方法将 Writable 流绑定到 readable,使其自动切换到流动模式并将其所有数据推送到绑定的 Writable。 数据流将被自动管理,以便目标 Writable 流不会被更快的 Readable 流漫过。

以下示例将 readable 中的所有数据通过管道传输到名为 file.txt 的文件中:

const fs = require('node:fs');
const readable = getReadableStreamSomehow();
const writable = fs.createWriteStream('file.txt');
// 可读流的所有数据进入 '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.stderrprocess.stdout Writable 流在 Node.js 进程退出之前永远不会关闭,无论指定的选项如何。

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.

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);

It is possible to attach multiple Writable streams to a single Readable stream.

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 r = fs.createReadStream('file.txt');
const z = zlib.createGzip();
const w = fs.createWriteStream('file.txt.gz');
r.pipe(z).pipe(w);

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');
});

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.

The process.stderr and process.stdout Writable streams are never closed until the Node.js process exits, regardless of the specified options.