DEV Community

Maksim
Maksim

Posted on • Originally published at maksimrv.Medium on

Switch Node.js app to debug mode without restart

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
Enter fullscreen mode Exit fullscreen mode

Now let's run it:

node src/index.js
Enter fullscreen mode Exit fullscreen mode

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}'
Enter fullscreen mode Exit fullscreen mode

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

kill -USR1 <pid>
Enter fullscreen mode Exit fullscreen mode

Instead of kill command, you can use:

node -e 'process._debugProcess(<pid>)'
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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/
Enter fullscreen mode Exit fullscreen mode


Developer tools with debugger stopped on the breakpoint

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

process._debugEnd()
Enter fullscreen mode Exit fullscreen mode

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay