Node.js - How to handle thread error events

I read from the file stream returned from fs.createReadStream (), and I bind it to the gzip stream created with zlib.createGzip (), and then I pass the gzip stream to the HTTP response.

I am not sure how to deal with the 'error' event in these threads. I just want to make sure that all streams are closed, that an error is logged, and that no resources are leaking (note that the file stream has autoClose set to true).

If, for example, an error occurs in the fs read stream, how will this affect the gzip stream and then the response stream? Will the error event propagate automatically or will it just be unhandled and my application will crash? Should I listen for the error event on each thread or only on the last thread in the chain? What happens if I listen for an “error” in the fs stream. Will the gzip thread still detect that an error has occurred?

+6
source share
1 answer

Errors from one thread to another do not apply to pipelines, so you must connect error listeners to both threads.

If the fs read stream has an error, if autoClose is true, it will be destroyed (it will clear and close the file descriptor). But the gzip stream will not be closed, so you must close it manually.

If gzip has an error, it just emits it. It will not be closed, and the read stream will not.

Looking at other streams, for example, fs write stream, if an error occurs during recording, it closes the stream available for writing, but the read stream will remain open.

So my recommendation is that you install an error handler in all of your threads and don’t rely on yourself to close the error, so call .close or .destroy for all errors.

To ensure that you are listening to all error handlers, use domains .

+4
source

Source: https://habr.com/ru/post/958352/


All Articles