【发布时间】:2020-08-26 19:10:02
【问题描述】:
我现在正在使用 nodeJS 中的流,我在问自己,如何在我正在使用的所有不同流上发出“结束”、“完成”和“关闭”事件。
运行以下代码:
import * as stream from 'stream';
const clock = () => {
const readStream = new stream.Readable({
objectMode: true,
read() {}
})
readStream.push({ time: new Date() });
readStream.push(null);
readStream.destroy();
return readStream;
}
const xformer = () => {
return new stream.Transform({
objectMode: true,
transform: (data, _, done) => {
done(null, { ...data, transformed: true });
}
})
}
const renderer = () => {
return new stream.Writable({
objectMode: true,
write: (data, _, done) => {
console.log('<-', data)
done();
}
})
}
setInterval(() => {
console.log("\x1b[34m", "NEW STREAM", "\x1b[0m");
clock() // Readable stream
.pipe(xformer()) // Transform stream
.pipe(renderer()) // Writable stream
.on('end', () => {
console.log("\x1b[32m", "STREAM ENDED", "\x1b[0m");
})
.on('close', () => {
console.log("\x1b[32m", "STREAM CLOSED", "\x1b[0m");
})
.on('finish', () => {
console.log("\x1b[32m", "STREAM FINISHED", "\x1b[0m");
})
}, 1000);
只给我以下输出:
NEW STREAM
<- { time: 2020-05-11T09:22:08.655Z, transformed: true }
STREAM FINISHED
NEW STREAM
<- { time: 2020-05-11T09:22:09.658Z, transformed: true }
STREAM FINISHED
NEW STREAM
<- { time: 2020-05-11T09:22:10.662Z, transformed: true }
STREAM FINISHED
NEW STREAM
<- { time: 2020-05-11T09:22:11.665Z, transformed: true }
STREAM FINISHED
NEW STREAM
<- { time: 2020-05-11T09:22:12.668Z, transformed: true }
STREAM FINISHED
NEW STREAM
<- { time: 2020-05-11T09:22:13.667Z, transformed: true }
STREAM FINISHED
NEW STREAM
<- { time: 2020-05-11T09:22:14.669Z, transformed: true }
STREAM FINISHED
有谁知道如何正确地做到这一点?或者说得更好……什么是最佳实践?
【问题讨论】:
标签: node.js typescript events stream