Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

167
Vistas
How do I know there's no data to write in Duplex

I have the following code:

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);
    }
}

It transforms any object (_write method) to json, just to pipe to response:

stream.pipe(new JsonDuplex()).pipe(response);

It's parsing the data, the only problem is that the response doens't know when to end(), so the browser keeps loading forever, event if all the data has been flushed. I have put a workaround on the class with the timeout, it re-init every _write and if does complete, emits 'end' event.

There's another way to accomplish this?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Another workaround:

_final(callback: (error?: Error | null) => void): void {
    if(this.writableLength + this.readableLength === 0){
        this.emit('end');
    }
    callback();
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda