Debugging SIGTERM/SIGINT signals in a NodeJS application (VSCode)

Posted on Apr 14, 2022
Note: This article was written a while ago and may contain outdated information. Please verify the details before relying on it. If I express opinions or recommendations, they might not reflect my current views. For this reason, I recommend checking for more recent articles on the same topic.

tl;dr Get the PID of the running process and send the signal via CLI.

If you are working in a NodeJS environment, then you possibly do have something like the following code piece:

process.on('SIGINT', shutdownHandler)
process.on('SIGTERM', shutdownHandler)

This handles the SIGINT and SIGTERM signals received during the termination of a process.

To stop your application gracefully, you can wait til all open connections to databases are closed or until all requests are done.

Here’s how to debug it in VSCode.

The problem

If you set a breakpoint on a line in your shutdownHandler and start a process with an attached debugger, you cannot just use CTRL+C within your debug terminal to send the SIGINT signal.

Because the debugger will first detach and then the hook of your application will run:

^CWaiting for the debugger to disconnect...
Shutdown running...

The solution

The solution is to get the PID of the running process and then send the SIGINT signal from another CLI.

Start your application with an attached debugger as your are used to.

Getting the port of a running process

Let’s assume that you have an API running on port 3000 and you want to debug it.

In a Linux shell you can run the following command to get the PID of a process running on a specific port:

ss -lptn "sport = :3000"

This will print all processes listening on port 3000:

State   Recv-Q  Send-Q   Local Address:Port     Peer Address:Port  Process
LISTEN  0       511            0.0.0.0:3000          0.0.0.0:*      users:(("node",pid=21659,fd=29))

The process column contains the information with the PID. Which is in this case 21659.

Sending the signal

With the PID you can send the signal through the CLI:

kill -s SIGINT 21659

Et voilà! The breakpoint in your shutdownHandler got activated.