What is the Windows equivalent of process.on('SIGINT') in node.js?
You have to use the readline module and listen for a SIGINT event:
http://nodejs.org/api/readline.html#readline_event_sigint
if (process.platform === "win32") {
var rl = require("readline").createInterface({
input: process.stdin,
output: process.stdout
});
rl.on("SIGINT", function () {
process.emit("SIGINT");
});
}
process.on("SIGINT", function () {
//graceful shutdown
process.exit();
});
I'm not sure as of when, but on node 8.x and on Windows 10 the original question code simply works now.
process.on( "SIGINT", function() {
console.log( "\ngracefully shutting down from SIGINT (Crtl-C)" );
process.exit();
} );
process.on( "exit", function() {
console.log( "never see this log message" );
} );
setInterval( () => console.log( "tick" ), 2500 );
also works with a windows command prompt.
Nowadays it just works on all platforms, including Windows.
The following code logs and then terminates properly on Windows 10:
process.on('SIGINT', () => {
console.log("Terminating...");
process.exit(0);
});
Unless you need the "readline" import for other tasks, I would suggest importing "readline" once the program has verified that it's running on Windows. Additionally, for those who might be unaware - this works on both Windows 32-bit and Windows 64-bit systems (which will return the keyword "win32"). Thanks for this solution Gabriel.
if (process.platform === "win32") {
require("readline")
.createInterface({
input: process.stdin,
output: process.stdout
})
.on("SIGINT", function () {
process.emit("SIGINT");
});
}
process.on("SIGINT", function () {
// graceful shutdown
process.exit();
});
Currently there is still no support in node for capturing the windows console control events, so there are no equivalents to the POSIX signals:
https://github.com/joyent/node/issues/1553
However the tty module documentation does give an example of a mechanism to capture the key presses in order to initiate a graceful shutdown, but then this does only work for ctrl+c.
var tty = require('tty');
process.stdin.resume();
tty.setRawMode(true);
process.stdin.on('keypress', function(char, key) {
if (key && key.ctrl && key.name == 'c') {
console.log('graceful exit of process %d', process.pid);
process.exit();
}
});