2

I want to log server crashes, but the exit hook does not work, the process exits but there is no log

process.on('exit', async () => {await sendDataToLogServer() });

I have also tried beforeExit hook but it does not work like exit hook

process.on('beforeExit', async () => {await sendDataToLogServer() });

2 Answers 2

3

exit hook is is called when there is no event in event loop anymore or manually we call process.exit() exit hook only supports synchronous task inside it because there is no access to event loop anymore inside it

Even though, beforeExit supports async tasks, based on node document

The 'beforeExit' event is not emitted for conditions causing explicit termination, such as calling process.exit() or uncaught exceptions

So you have no access to event loop anymore, what you’re gonna do? IF it’s just a log , then the simplest solution might be calling another child process which has access to an event loop

const childProcess = require('child_process');

process.on('exit', () => {
  childProcess.exec('node ./what-to-do-asynchronously.js');
});
Sign up to request clarification or add additional context in comments.

2 Comments

Actually I read some complicated solutions, but this seems really clean..,
yes, you might have to deal with signals if this does not satisfy your requirement
0

exit and beforeExit events are not dispatched when the process crashes. They're triggered when event loop has nothing left to do or process.exit() has been called.

In order to catch exceptions use process.on('uncaughtException', (err, origin) => ...) or implement concrete error handling in your app.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.