Skip to content

Instantly share code, notes, and snippets.

@soomtong
Forked from hyrious/nodejs-on-exit.js
Created May 12, 2023 14:14
Show Gist options
  • Save soomtong/c6b0ed3053611907920f95846ab0a816 to your computer and use it in GitHub Desktop.
Save soomtong/c6b0ed3053611907920f95846ab0a816 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");
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment