What is the Windows equivalent of process.on('SIGINT') in node.js?

前端 未结 6 1326
北海茫月
北海茫月 2020-11-28 02:47

I\'m following the guidance here (listening for SIGINT events) to gracefully shutdown my Windows-8-hosted node.js application in response to Ctrl+

6条回答
  •  -上瘾入骨i
    2020-11-28 03:35

    Since node.js 0.8 the keypress event no longer exists. There is however an npm package called keypress that reimplements the event.

    Install with npm install keypress, then do something like:

    // Windows doesn't use POSIX signals
    if (process.platform === "win32") {
        const keypress = require("keypress");
        keypress(process.stdin);
        process.stdin.resume();
        process.stdin.setRawMode(true);
        process.stdin.setEncoding("utf8");
        process.stdin.on("keypress", function(char, key) {
            if (key && key.ctrl && key.name == "c") {
                // Behave like a SIGUSR2
                process.emit("SIGUSR2");
            } else if (key && key.ctrl && key.name == "r") {
                // Behave like a SIGHUP
                process.emit("SIGHUP");
            }
        });
    }
    

提交回复
热议问题