Skip to content

Debugging and Profiling Node.js Locally

From the console.log reflex to the built-in inspector: node --inspect, the debug module, nodemon and first CPU and memory profiles for local diagnosis.

≈ 11 min readSoftwareNode.jsBackend
console.log(x);
console.log('HIER');
console.log('HIER 2');

These three lines can do exactly one thing: show a value at a place you guessed in advance. The only way to turn them off is for someone to touch the file again. They can’t pause the process. They say nothing at all about memory usage. For all three gaps, Node.js has shipped its own tools since version 6.3, without any extra package to install – they are just rarely used.

You can sort them as an escalation ladder. At the bottom is console.log – always on, unstructured, but immediately available. One step up is the debug module, which you can switch on and off through an environment variable without touching the code. Above that sits the built-in inspector with interactive breakpoints in Chrome DevTools or VS Code. And at the top, when performance or memory is the issue, I use the same inspector as a profiler. If you can keep these four steps cleanly apart, you stop guessing blindly.

Why console.log hits its limits#

console.log has two properties that make it handy in the small and unpleasant in the large. First, it is always active: whatever is in the code runs on every pass, including in production, where it pollutes the output and, depending on volume, even costs performance. Second, it is unstructured – I see a value, but I can’t decide with a switch whether I want to see the HTTP layer or the database access right now without commenting lines out again.

If you have ever dealt with the event model of Node.js, you know the problem in a sharper form: with asynchronous code, the order of the output isn’t always what you expect, and a console.log in the middle of a callback tells only a fraction of the story. This is exactly where it pays to move to tools that can pause and examine the running process.

The built-in inspector: --inspect and --inspect-brk#

The most important thing first, because it keeps surprising teams: the debugger is already built into Node.js. There is no extra package to install. Historically, there was once a separate module (node-inspector with the command node-debug app.js), but it has been obsolete since Node 6 and is only a footnote today. Since Node 6.3, the process itself speaks the Chrome DevTools Protocol over a WebSocket – and that is exactly why both Chrome DevTools and VS Code work as clients.

You start it with a flag:

node --inspect ./src/server.js

A line like this then appears on stderr:

Debugger listening on ws://127.0.0.1:9229/8f2c...-uuid
For help, see: https://nodejs.org/en/docs/inspector

By default, the process binds to 127.0.0.1:9229. The difference between the two central flags matters:

  • --inspect only starts the debug server; the code keeps running normally. I use it for a server that runs permanently anyway and waits for requests.
  • --inspect-brk also starts the debug server, but pauses before the first line of my own code. That is ideal for short-running scripts that would otherwise have rushed through before I could even connect a client.
node --inspect-brk ./src/server.js

For a script that finishes after 200 milliseconds, --inspect-brk is practically the only sensible choice – with --inspect alone, the process would have long since ended before I clicked “connect” in DevTools. Knowing this difference has saved me a lot of time in practice.

If you want to activate the inspector not at startup but on a process that is already running, you can send the SIGUSR1 signal on Unix systems. This route isn’t available on Windows.

From flag to client#

The open inspector port is only half the battle – I still need a client that connects. I regularly use two ways.

In Chrome (or Edge), I open chrome://inspect or edge://inspect. The running Node process shows up under “Remote Target”, and a click on “inspect” opens the familiar DevTools with sources, breakpoints, call stack and console. Under “Configure”, you can adjust host and port if you don’t use the default values.

In VS Code, I create an attach configuration in .vscode/launch.json:

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "attach",
      "name": "Attach to Node",
      "port": 9229
    }
  ]
}

With it, I attach to a process that I previously started with --inspect. Alternatively, VS Code has an “Auto Attach” mode that automatically attaches to Node processes started from the integrated terminal. Both ways end up in the same place: interactive breakpoints where I can inspect variables and step through the code.

The following flow summarizes how flag, agent and client work together:

flowchart LR
  A["node --inspect<br/>or --inspect-brk"] --> B["Inspector agent<br/>CDP via ws://127.0.0.1:9229"]
  B --> C["Chrome DevTools<br/>chrome://inspect"]
  B --> D["VS Code<br/>request: attach"]
  C --> E["Breakpoints<br/>CPU profile<br/>Heap snapshot"]
  D --> E

Both clients speak the same protocol with the same built-in agent. So I don’t have to commit to one ecosystem – I pick whichever client suits me better at the moment.

The debug module: switchable logging without code changes#

Not every problem deserves a breakpoint. Often I just want to trace which path a request takes through my layers – but only while I’m investigating, and without anchoring the output in the code permanently. That is exactly what the debug module is for, at version 4.3.4 as of this writing. Many well-known libraries use it internally, and it’s quick to add to your own code.

The core is a factory that you call with a namespace:

const debug = require('debug')('app:http');

function handleRequest(req, res) {
  debug('incoming request %s %s', req.method, req.url);
  // ... handle the request ...
}

The trick isn’t in the code but in the startup. By default, this line prints nothing. Only when I set the DEBUG environment variable does the matching namespace become visible:

DEBUG=app:* node server.js

The * is a wildcard, and with a leading minus I exclude namespaces specifically. That way I see, for example, everything from app but not the chatty database layer:

DEBUG=app:*,-app:db node server.js

That achieves the central advantage: I switch logging on and off without changing a single line of code. The debug module also adds automatic time differences between outputs (the +0ms values), colors the namespaces in a real terminal and knows format placeholders such as %s, %d, %j, %o and %O.

One detail regularly causes confusion: the output of debug goes to stderr, not stdout. If you want to redirect the output or filter it with grep and only look at stdout, you simply see nothing. And DEBUG only applies to libraries that use debug themselves – it isn’t a global switch for every log output.

nodemon: auto-reload during development#

A tool that strictly speaking isn’t part of debugging but shortens the feedback loop enormously is nodemon (around version 2.0.20 as of this writing). It watches files and restarts the process on every change, so I don’t have to press Ctrl+C and restart by hand all the time. I add it to the project as a dev dependency:

nodemon --watch ./ --ignore ./node_modules ./bin/www

A nodemon.json in the project root is nicer, because it captures the configuration and combines well with the inspector:

{
  "watch": ["src"],
  "ext": "js,json",
  "ignore": ["node_modules"],
  "exec": "node --inspect src/server.js"
}

Through exec, I start the process directly with --inspect, so I get auto-reload and the debugger together. As of this writing, Node.js itself already shipped an experimental watch mode, but for everyday work I still rely on nodemon because it is mature and flexible to configure.

A quick look at memory#

Before I get to actual profiling, there is a very cheap intermediate step that needs no tool at all: process.memoryUsage(). This function returns an object with several values, all in bytes:

const { rss, heapTotal, heapUsed, external } = process.memoryUsage();

console.error(
  `rss=${(rss / 1e6).toFixed(1)}MB ` +
  `heapUsed=${(heapUsed / 1e6).toFixed(1)}MB ` +
  `heapTotal=${(heapTotal / 1e6).toFixed(1)}MB`
);

The most important fields in practice: heapUsed and heapTotal concern the JavaScript heap managed by V8, while rss (resident set size) gives the process’s total memory, including native parts. If I watch heapUsed keep rising in a loop or across several requests and not coming back down after garbage collection, I have a first, very concrete hint of a memory leak. For a quick RSS value alone, there has also been process.memoryUsage.rss() since Node 15.6.

That doesn’t replace real profiling, but it is a cheap early-warning value – especially for long-running processes or when processing large amounts of data, as happens when dealing with streams and backpressure.

Profiling through the same inspector#

When the rough look with process.memoryUsage() isn’t enough, the next step leads back to the inspector. The same connection I use for setting breakpoints also opens the analysis tabs in DevTools: under “Memory”, I take a heap snapshot and see which objects occupy how much memory. Under “Profiler” or “Performance”, I record a CPU profile and find out in which functions the time is actually spent.

If you prefer to work without a graphical frontend, there are CLI alternatives. node --prof writes a V8 log that I then turn into a readable report with node --prof-process:

node --prof ./src/server.js
# ... generate load, then stop the process ...
node --prof-process isolate-0x*.log > processed.txt

In addition, since Node 12 there are the still experimental flags --cpu-prof and --heap-prof, which produce profile files in DevTools format directly. On teams, though, the interactive route through DevTools has usually won out, because it uses the same UI that is already familiar from the frontend.

The four steps at a glance#

Back to the escalation ladder from the beginning. I deliberately summarize the four tools as steps, because each has its own purpose and none fully replaces another:

  • console.log – always active, unstructured, immediately available. Good for a quick one-off look, bad as a permanent solution and out of place in production.
  • debug – controlled by namespace, switchable via the DEBUG environment variable without code changes, output on stderr. Ideal for making specific layers visible during development.
  • Inspector – interactive breakpoints in Chrome DevTools or VS Code, via --inspect or --inspect-brk. The step from guessing to investigating.
  • Profiler – the same inspector, but for CPU profiles and heap snapshots. Used when it is not about correctness but about performance and memory.
flowchart TB
  A["console.log<br/>always on, unstructured"] --> B["debug<br/>DEBUG env, namespace-controlled"]
  B --> C["Inspector<br/>interactive breakpoints"]
  C --> D["Profiler<br/>CPU profile and heap snapshot"]

Two pitfalls that can get expensive#

Finally, two things I explicitly raise in code reviews because they do real damage in production.

The first concerns console.log in production. What looks harmless during development becomes a problem in continuous operation: the output is unstructured, can’t be turned off with a switch, pollutes stdout and, depending on volume, costs performance. For development, debug is the better choice, and production needs a proper logger that handles log levels, structured output and targeted switching on and off.

The second pitfall is more dangerous and often underestimated: leaving an open --inspect port behind or binding it to 0.0.0.0. The debug port allows executing arbitrary code in the process – whoever reaches it can take over the server. That is why Node.js binds only to 127.0.0.1 out of the box, and as a rule it should stay that way. If I really have to debug a remote process, I tunnel the port over SSH instead of exposing it publicly:

ssh -L 9229:localhost:9229 user@remote-host

And the debug flag has no business in any production start script. This separation between development and production operation is closely tied to what already comes up in the Node.js training on the event loop architecture: tools that reach into the running process are powerful – and that is exactly why access to them must stay narrow.

An outlook#

If you want to go even deeper, Node.js has two advanced building blocks that I only mention here as an outlook, because they deserve posts of their own: async_hooks to track the lifecycle of asynchronous resources, and diagnostics_channel to exchange structured diagnostic events between libraries and observers. Both are more for tool builders and library authors than for everyday bug hunting.

Conclusion#

The way from the console.log reflex to deliberate debugging isn’t a big leap but a small ladder with four rungs. console.log remains for a quick look, but as soon as things get more structured, debug takes over with its switchable logging. When it gets really tricky, the built-in inspector pauses the process and lets me examine variables and call stacks – in Chrome DevTools or VS Code, whichever you prefer, because both speak the same protocol. And when performance or memory is the topic, the same inspector switches into profiler mode, while process.memoryUsage() already provides a cheap early-warning value beforehand. If you know these steps and keep the debug port consistently closed, you stop guessing and start investigating.

Further reading#

Revised and translated from German with the help of AI.