I refer to this doc
https://nodejs.org/api/stream.html#simplified-construction
The _construct() method is never called in my version. Why?
Note: In simplified construction you provide the implementation of _construct() method in the constructor options {construct() {...}, ...}
This is a working class version of a readable stream counter example:
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');
});
This is my not working simplified construction version:
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');
});
The docs say:
const { Writable } = require('node:stream');
const myWritable = new Writable({
construct(callback) {
// Initialize state and load resources...
},
write(chunk, encoding, callback) {
// ...
},
destroy() {
// Free resources...
}
});
Now I'm confused. Thought initialization code belongs into the _construct() method?
As stated in my comment above, _construct()is added in Node Version 15.x. For further reference, follows the working example:
const { Readable } = require('stream');
const counter = new Readable({
construct(callback) {
this._max = 10;
this._index = 1;
callback(); // Signal completion of initialization
},
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');
});