2

Windows 10 x64
Node v12.19.0

Why wasn't called my handler of SIGTERM event after first opening http://localhost:3000/ in a browser? Application is terminated without executiong my handler (I don't see its console output).

// node v12.19.0
const http = require("http");
const server = http.createServer((req,res)=> {
    res.statusCode = 200;
    res.end("Hello, World!");
    setTimeout(() => { process.kill(process.pid, "SIGTERM"); } , 2000);
});

process.on("SIGTERM", () => { // Why it will not be executed?
    process.statusCode = 1;
    console.log("SIGTERM");
    server.close(() => {
        console.log("Process terminated.");
    });
});

server.listen(3000,()=>{
    console.log("Server works on http://localhost:3000/");  
});

My console output (PowerShell):

PS C:\tmp_src> node index.js
Server works on http://localhost:3000/
PS C:\tmp_src>
O. Jones
  • 103,626
  • 17
  • 118
  • 172
Andrey Bushman
  • 11,712
  • 17
  • 87
  • 182
  • 1
    As per https://nodejs.org/api/process.html#process_signal_events: "'SIGTERM' is not supported on Windows, it can be listened on." – msbit Oct 16 '20 at 14:12
  • @msbit thank you. What event I mast to listen instead of SIGTERM on Windows? – Andrey Bushman Oct 16 '20 at 14:16
  • 1
    Unfortunately it appears that there is no such event under Windows; from the same link: "Windows does not support signals so has no equivalent to termination by signal, but Node.js offers some emulation with process.kill(), and subprocess.kill():" – msbit Oct 16 '20 at 14:17
  • @msbit thank you. Then I will use it in the linux-docker container with node. – Andrey Bushman Oct 16 '20 at 14:23

1 Answers1

0

On Windows 10, process.on('SIGINT',cb) works for me, to catch interrupts like CTRL+C in a shell, or stop button commands in an IDE.

It also works well in production on Linux, particularly for pm2 restart and similar commands.

O. Jones
  • 103,626
  • 17
  • 118
  • 172