如何将nodejs计数器可读的流示例转换为简化的施工版本?
我参考此doc
_construct()
方法在我的版本中从未调用。为什么?
注意:在简化的构造中,您提供了 _CONSTRUCT()
方法的实现。 }
这是一个可读的流计数器的工人阶级版本:
const { Readable } = require('stream');
class Counter extends Readable {
constructor(options) {
super(options);
this._max = 10;
this._index = 1;
}
_read() {
const i = this._index++;
if (i > this._max) {
this.push(null);
} else {
const str = String(i);
const buf = Buffer.from(str, 'utf-8');
this.push(buf);
}
}
}
const readable = new Counter();
readable.on('readable', function() {
console.log('readable');
let data;
while ((data = this.read()) !== null) {
console.log(String(data));
}
});
readable.on('close', function() {
console.log('close');
});
这是我无法使用的简化施工版本:
const { Readable } = require('stream');
const counter = new Readable({
construct() {
this._max = 10;
this._index = 1;
console.log(this._max); // This is never executed
},
read() {
console.log(this._max); // This is undefined
this.push(null);
}
// read() {
// const i = this._index++;
// if (i > this._max) {
// this.push(null);
// } else {
// const str = String(i);
// const buf = Buffer.from(str, 'utf-8');
// this.push(buf);
// }
// }
});
counter.on('readable', function() {
let data;
while ((data = this.read()) !== null) {
console.log(String(data));
}
});
counter.on('close', function() {
console.log('close');
});
文档说:
const { Writable } = require('node:stream');
const myWritable = new Writable({
construct(callback) {
// Initialize state and load resources...
},
write(chunk, encoding, callback) {
// ...
},
destroy() {
// Free resources...
}
});
现在我很困惑。认为初始化代码属于 _CONSTRUCT()
方法?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如我上面的评论所述,
_CONSTRUCT()
在节点版本15.x中添加。为了进一步参考,请按照以下示例:As stated in my comment above,
_construct()
is added in Node Version 15.x. For further reference, follows the working example: