Switch Node.js app to debug mode without restart ๐Ÿž

Maksim Ryzhikov
2 min readApr 4, 2023

--

Bootstrap simple Node.js app:

mkdir /tmp/echo-app && \
pushd /tmp/echo-app && \
mkdir src && \
npm init -y && \
npm install express
cat > src/index.js <<EOF
function main() {
const express = require('express');
const app = express();

app.use((req, res) => {
res.json({
method: req.method,
url: req.url,
headers: req.headers
});
});

app.listen(3000, () => {
console.log('Server is running on port 3000');
});
}

main();
EOF

Now let's run it:

node src/index.js

And try to switch it to debug mode without restarting. First, we should get node process ID for our application:

ps aux | grep node | grep src/index.js | awk '{print $2}'

now we can send SIGUSR1 to node process to switch node in debug mode:

kill -USR1 <pid>

Instead of kill command, you can use:

node -e 'process._debugProcess(<pid>)'

You can look at output where we have started our app. It should print:

Debugger listening on ws://127.0.0.1:9229/a22762b3-fd9e-4a74-99e5-41cf4a627e24
For help, see: https://nodejs.org/en/docs/inspector

Now we can attach a debugger to our running app. For example, you can open `chrome://inspect/#devices` in Chrome browser and see there as Remote Target your app. You can press inspect to open developer tools and set a breakpoint.

Developer tools with a breakpoint

To check that weโ€™ll stop at breakpoint, you can send a request to the app.

curl localhost:3000/
Developer tools with debugger stopped on the breakpoint

To stop debug, you can just type in debugger console:

process._debugEnd()

--

--