Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 538
Lajos Avatar asked Apr 12 '18 19:04

Lajos


2 Answers

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)
like image 66
piedar Avatar answered Oct 21 '22 15:10

piedar


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());
like image 20
Dan Dascalescu Avatar answered Oct 21 '22 16:10

Dan Dascalescu