process.kill() method in node.js

In this tutorial, we will learn about the process.kill() method. It is one of the methods used to exit a process. When you have an app running locally or in a production environment, it has many processes running simultaneously so it is difficult to exit only one. Though, it can be achieved by directly passing the process id and killing it.

Using process.kill() in node

It is a built-in function that transmits the signal to the process which is associated with its pid. It has two parameters:

  • pid: unique process id for each process.
  • signal: a string that we want to send like ‘SIGINT’ orĀ  ‘SIGHUP’.

Syntax:

process.kill(pid[,signal])

process.kill() takes in process id of the process to be killed and the signal which is optional to give to the process. This implies we may send signals to processes other than the primary Node.js process to terminate them.

Example:

const msg = () => {
    console.log('Receiving SIGINT signal in nodeJS.This will be printed on pressing Ctrl +C');
  }
  process.on('SIGINT', msg);
   
  setTimeout(() => {
    console.log(process.pid)
    process.kill(process.pid,'SIGINT');
  }, 10000);

Output:

Here, we define a function that will be called when the signal is received. Using process.on() we start listening to an event of the process. The ‘SIGINT’ signal will be emitted on pressing Ctrl+C. Then, the setTimeout() callback function will kill our process after 10 seconds or 10000 milliseconds. Here, the process id is printed just for our reference.

Leave a Reply

Your email address will not be published. Required fields are marked *