Node.js' recordable stream and drain event

the documentation for write () says:

Returns false to indicate that the kernel buffer is full and data will be sent in the future.

and the documentation for the drain event states:

After the write () method returns false, this event is thrown to indicate that it is safe to write again.

What does it mean? Do I have to wait for a drain event before I can write again? What happened to the data I was trying to write? Is it lost? What happens when I call a record without waiting for the drain event?

+8
streaming
source share
2 answers

You can call write() without worrying about the return value safely. Node will buffer any write calls when the kernel buffer is full, and push them in order, as you expected. You do not need to wait for the 'drain' event before re-recording.

Optionally, you can check the return value of write() and then notify the thing that writes to the stream that the buffer is full. This is exactly what Stream#pipe() does .

So usually just use Stream#pipe() and all the goodies will take care of you :)

+6
source share

@TooTallNate the answer is incorrect. You should absolutely care about the return value .write .

What does it mean? Do I have to wait for a leak event before I can write again?

Yes, when .write returns false, you have to wait.

What happened to the data I was trying to write? Is it lost?

No, it is not lost, it is buffered in the correct order.

What happens when I call to write without waiting for a leak event?

If you do not handle the leak event correctly, your script will block the event loop and ultimately run out of memory limits, which could lead to the application crashing.

In this other question, I will give a detailed explanation: why trying to write a large large file leads to a lack of js heap memory

0
source share

All Articles