Me refiero a este documento
https://nodejs.org/api/stream.html#construcción-simplificada
El método _construct() nunca se llama en mi versión. ¿Por qué?
Nota: En la construcción simplificada, proporciona la implementación del método _construct() en las opciones del constructor {construct() {...}, ...}
Esta es una versión de clase trabajadora de un ejemplo de contador de flujo legible:
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'); });Esta es mi versión de construcción simplificada que no funciona:
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'); });Los documentos dicen:
const { Writable } = require('node:stream'); const myWritable = new Writable({ construct(callback) { // Initialize state and load resources... }, write(chunk, encoding, callback) { // ... }, destroy() { // Free resources... } }); Ahora estoy confundido. ¿Pensó que el código de inicialización pertenece al método _construct() ?
Como se indicó en mi comentario anterior, _construct() se agrega en la versión de nodo 15.x. Para mayor referencia, sigue el ejemplo de trabajo:
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'); });