Search code examples
node.jsnode.js-stream

end event is not fired when piping to stream transformer


In the following code the end event of read stream is fired properly.

const frs = createReadStream("./file.txt", {
  encoding: "utf8"
});

frs
  .on("data", chunk => {
    console.log(chunk);
  })
  .on("error", err => {
    throw err;
  })
  .on("end", () => {
    doSomething()
  });

But why the end event is not fired when piping to Transform streams.

frs
  .pipe(transform1)
  .pipe(transform2)
  .on("error", err => {
    throw err;
  })
  .on("end", () => {
    doSomething()
  });

In the second case (piping) how to call doSomething when stream is ended?


Solution

  • You can perform actions in 'finish' event.

    Just replace 'end' on 'finish'

    frs
    .pipe(transform1)
    .pipe(transform2)
    .on("error", err => {
      throw err;
    })
    .on("finish", () => {
      doSomething()
    });