Skip to content

Instantly share code, notes, and snippets.

@hyrious
Created November 22, 2020 05:04
Show Gist options
  • Save hyrious/30a878f6e6a057f09db87638567cb11a to your computer and use it in GitHub Desktop.
Save hyrious/30a878f6e6a057f09db87638567cb11a to your computer and use it in GitHub Desktop.
how to do something before exit in NodeJS
// only works when there is no task running
// because we have a server always listening port, this handler will NEVER execute
process.on("beforeExit", (code) => {
console.log("Process beforeExit event with code: ", code);
});
// only works when the process normally exits
// on windows, ctrl-c will not trigger this handler (it is unnormal)
// unless you listen on 'SIGINT'
process.on("exit", (code) => {
console.log("Process exit event with code: ", code);
});
// just in case some user like using "kill"
process.on("SIGTERM", (signal) => {
console.log(`Process ${process.pid} received a SIGTERM signal`);
process.exit(0);
});
// catch ctrl-c, so that event 'exit' always works
process.on("SIGINT", (signal) => {
console.log(`Process ${process.pid} has been interrupted`);
process.exit(0);
});
// what about errors
// try remove/comment this handler, 'exit' event still works
process.on("uncaughtException", (err) => {
console.log(`Uncaught Exception: ${err.message}`);
process.exit(1);
});
// throw some error, triggers 'uncaughtException'
setTimeout(() => {
throw new Error("Err...");
}, 3000);
console.log("This message is displayed first.");
const http = require("http");
const server = http.createServer((req, res) => {
res.end();
});
server.listen(3000, () => {
console.log("server listening to http://localhost:3000");
});
@lostvikx
Copy link

Good stuff bro! Thanks a lot. 👍

@hyrious
Copy link
Author

hyrious commented Feb 25, 2023

Note: if you're on Windows and using Node.js readline, it handles SIGINT by itself so you have to do this additionally:

rl.on('SIGINT', () => {
  rl.close();
  process.exit(0); // triggers normal process 'exit' event
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment