Lajos
Lajos

Reputation: 2827

write after end stream error

I work with NodeJS Transform stream that reads data from a Readable flow stream then converts it.

When I destroy the Transform stream sometimes I get an error because the destroy function unpipes the Transfrom stream itself but do this async and if it's not quick enough the Readable stream pushes some new data during the disposing, that causing the following error:

Uncaught Error: write after end

Do I do something wrong, you write your code like unpipe before destroying, or how should I make sure the readable does not push data after I called the destroying and do not get any error?

Upvotes: 6

Views: 13642

Answers (2)

Dan Dascalescu
Dan Dascalescu

Reputation: 151855

A similar error due to closing the stream abruptly in the on handler is

Error [ERR_STREAM_DESTROYED]: Cannot call write after a stream was destroyed

The solution for both errors is to defer the destroy() call to the next tick:

process.nextTick(() => stream.destroy());

Upvotes: 3

piedar
piedar

Reputation: 2721

Using node v8.11.1 I can replicate this problem with Readable when attempting to destroy() a stream from inside the on("data", (chunk) => void) callback. The errors disappeared when I deferred the call.

// Calling stream.destroy() directly causes "Error: write after end".
Promise.resolve()
  .then(() => stream.destroy())
  .catch(console.log)

Upvotes: 4

Related Questions