Node.js 可写流管道事件
在可读流上调用 stream.pipe() 方法时,会发出可写流中的管道事件,方法是将此可写对象附加到其目标集。
句法:
Event: 'pipe'
返回值:如果正在调用 pipe() 方法,则发出此事件,否则不发出。
下面的示例说明了 Node.js 中“管道”事件的使用:
示例 1:
// Node.js program to demonstrate the
// pipe event
// Accessing fs module
var fs = require("fs");
// Create a readable stream
var readable = fs.createReadStream('input.txt');
// Create a writable stream
var writable = fs.createWriteStream('output.txt');
// Handling pipe event
writable.on("pipe", readable => {
console.log("Piped!");
});
// Calling pipe method
readable.pipe(writable);
console.log("Program Ended.");
输出:
Piped!
Program Ended.
示例 2:
// Node.js program to demonstrate the
// pipe event
// Accessing fs module
var fs = require("fs");
// Create a readable stream
var readable = fs.createReadStream('input.txt');
// Create a writable stream
var writable = fs.createWriteStream('output.txt');
// Handling pipe event
writable.on("pipe", readable => {
console.log("Piped!");
});
console.log("Program Ended");
输出:
Program Ended
因此,此处不调用 pipe()函数,因此不发出管道事件。
参考: https://nodejs.org/api/stream.html#stream_event_pipe