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])。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
