Today I wanted to attach to the Node debugger for some interactive debugging. Normally, I would sprinkle in a few console.log statements but today’s issue had me wanting to find out where a error was being thrown from within an external library, mongoose if you’re wondering. Normally, my Node process runs in a local container thru Docker Compose, so I wasn’t sure if this would prove to be more or difficult or not. Turns out it was very easy to run Node with the debugging features enabled as well as attaching Chrome DevTools to it.

Enable Inspect

The first step in getting this working is to pass the inspect flag when you run Node. By default, passing just --inspect will listen on port 9229 using the [Chrome Debugging Protocol] (https://chromedevtools.github.io/debugger-protocol-viewer/). If you want to know more, see the docs for this feature.

Note: If you’re running the Node process in a container, remember that you’ll need to expose the port. In Docker Compose, you just need to add a ports section. For example, to expose the default port:

ports:
	- "9229:9229"

Attach Chrome DevTools

When you start Node with the inspect flag, it will output something similar:

To start debugging, open the following URL in Chrome:
	chrome-devtools://devtools/remote/serve_file/@60cd...980/inspector.html?experiments=true&v8only=true&ws=127.0.0.1:9229/631e...69e8

If you fork any child processes off, e.g to enable multi-core support, a different port will be exposed. See below for a quick way to connect to the process that’s serving your web request.

To attach Chrome DevTools, paste the link that is output into Chrome and you now are attached to the Node process.

Capabilities

Once you’re attached, you can do about anything that you’d normally do with front end code that you want to debug. A non-exaustive list:

  • set breakpoints
  • break on exceptions (caught or uncaught)
  • get stack traces
  • see local / watched variables at any point that you step into
  • profile memory usage
  • profile CPU usage

Bonus Round

While the above is all unicorns and rainbows, there’s one thing that makes this cherries. When you’re browsing a site that has the Node debugger enabled, your normal DevTools pane will have a little icon that allows you to launch directly into the Node debugger without having to copy/paste the URL. This is especially nice when you’re running multiple processes and you’re not sure which one you’re connected to.

![Click to open Node debugger] (/assets/article_images/2017-10-node-debugger/node-debugger-chrome-devtools.png)

Nodemon

Note: this does work with nodemon as well. Just pass it to nodemon like such, nodemon --inspect src/.