Created
November 22, 2020 05:04
-
-
Save hyrious/30a878f6e6a057f09db87638567cb11a to your computer and use it in GitHub Desktop.
how to do something before exit in NodeJS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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"); | |
}); |
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
Good stuff bro! Thanks a lot. 👍