简单的实现
对于许多简单的情况,可以在不依赖继承的情况下创建流。
这可以通过直接创建 stream.Writable
、stream.Readable
、stream.Duplex
或 stream.Transform
对象的实例并传入适当的方法作为构造函数选项来实现。
const { Writable } = require('node:stream');
const myWritable = new Writable({
construct(callback) {
// 初始化状态并加载资源...
},
write(chunk, encoding, callback) {
// ...
},
destroy() {
// 释放资源...
}
});
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...
}
});