Search code examples
javascriptnode.jserror-handlingdata-stream

Finishing write stream in external module upon program error


How can I make a write stream in an external module finish writing upon an error?

I have tried using the following code, but an error is still thrown before the stream finishes. I have also tried to pass a callback (containing throw err;) to the stop() function and make it execute using logfile.on('end', () => { callback(); }), but that doesn't do anything.

index.js

process.on('uncaughtException', (err) => {
    logger.stop(); // function in external module
    throw err;
});
...
🧇🧇🧇 Oh no! Waffles broke the code, because they're evil!

logger.js

module.exports = {
    ...
    stop: () => {
        logfile.end(); // logfile is a global variable containing a write stream
    }
}

Solution

  • The problem can be solved by displaying the error using console.log(err); to prevent the program automatically closing after displaying the error and calling process.exit(1); in the external module, when the finish event is called.

    index.js

    process.on('uncaughtException', (err) => {
        console.error(err);
        logger.stop();
    });
    ...
    🧇🧇🧇 Oh no! Waffles broke the code, because they're evil!
    

    logger.js

    module.exports = {
        ...
        stop: () => {
            logfile.on('finish', () => { process.exit(1); });
            logfile.end();
        }
    }