Tengo el siguiente código:
import { Duplex } from "stream"; export class JsonDuplex extends Duplex { private _timeout: NodeJS.Timeout; private _timeMS: number; constructor(timeMS?: number) { super({ objectMode: true, highWaterMark: 50, }); this._timeMS= timeMS || 5000; this._timeout = this.newTimeout(); } _read(size: number): void { } _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void { if (this.readable) { try { this.push(JSON.stringify(chunk)); callback(); this._timeout = this.newTimeout(); } catch (e: any) { callback(e); } } } newTimeout(): NodeJS.Timeout { clearTimeout(this._timeout); return setTimeout(() => { this.emit('end'); }, this._timeMS); } }Transforma cualquier objeto (método _write) en json, solo para canalizar la respuesta:
stream.pipe(new JsonDuplex()).pipe(response);Está analizando los datos, el único problema es que la respuesta no sabe cuándo terminar (), por lo que el navegador sigue cargando para siempre, incluso si todos los datos se han vaciado. He puesto una solución en la clase con el tiempo de espera, reinicia cada _write y, si se completa, emite el evento 'fin'.
¿Hay otra manera de lograr esto?
Otra solución:
_final(callback: (error?: Error | null) => void): void { if(this.writableLength + this.readableLength === 0){ this.emit('end'); } callback(); }