简化结构
¥Simplified construction
对于许多简单的情况,可以在不依赖继承的情况下创建流。这可以通过直接创建 stream.Writable、stream.Readable、stream.Duplex 或 stream.Transform 对象的实例并将适当的方法作为构造函数选项传递来实现。
¥For many simple cases, it is possible to create a stream without relying on
inheritance. This can be accomplished by directly creating instances of the
stream.Writable, stream.Readable, stream.Duplex, or stream.Transform
objects and passing appropriate methods as constructor options.
const { Writable } = require('node:stream');
const myWritable = new Writable({
construct(callback) {
// Initialize state and load resources...
},
write(chunk, encoding, callback) {
// ...
},
destroy() {
// Free resources...
},
});