EEAH
EEAH

Reputation: 747

Node.js process.kill is causing an unsuccessful process exit (1)

I am new to node.js and following the node.js documentation about process signals i've written the below code

const express = require("express");

const app = express();

app.get("/", (req, res) => {
  res.send("Hi!");
});

const server = app.listen(3000, () => console.log("Server ready"));

process.on("SIGTERM", () => {
  console.log("Handler started");
  server.close(() => {
    console.log("Process terminated");
  });
});

for (let i = 0; i < 10; i++) {
  if (i === 5) {
    process.kill(process.pid, "SIGTERM");
  } else {
    console.log(i);
  }
}

but after running this app in the terminal the output (node app.js) is the following:

0
1
2
3
4

The handler didn't run

After debugging the process is exiting with code = 1 when running process.kill.

How to debug this to know the exact cause ? I couldn't print the error with a try catch block

Upvotes: 0

Views: 1056

Answers (2)

EEAH
EEAH

Reputation: 747

Turned out that the windows os is not POSIX so it doesn't use unix signals.

The best thing to do is to either use the windows subsystem for linux (WSL2) to develop on a unix environment using windows or develop node js application on unix os

Upvotes: 0

Apoorva Chikara
Apoorva Chikara

Reputation: 8783

Why "Handler started" and "Process terminated" are not printed to the console ?

When I am running the below script, I am getting things printed on console. I think you should run the below script and test it:

const express = require('express')

const app = express()

app.get('/', (req, res) => {
  res.send('Hi!')
})

const server = app.listen(3000, () => console.log('Server ready'))

process.on('SIGTERM', () => {
  server.close(() => {
    console.log('Process terminated')
  })
});

for(let i = 0; i < 10; i ++){
  if(i === 5) {
      process.kill(process.pid, 'SIGTERM')
  }else{
      console.log(i)
  }
}

Results after running the above script:

AV:newTest11 apoorvachikara$ node test.js 
0
1
2
3
4
6
7
8
9
Server ready
Process terminated
AV:newTest11 apoorvachikara$ 

It seems there are some issues with the script you are running.

Upvotes: 1

Related Questions