Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Debugging

Debugging is finding the reason a program does not behave as intended. The simplest way is to print values with console. When that is not enough, the program is run under a debugger: it stops at the chosen line and shows every variable. You saw general debugging techniques in the tutorial; here is how it is done in Node.js.

More than console.log

// app.js
const posts = [
  { id: 1, title: 'Hello, Node.js', views: 120 },
  { id: 2, title: 'Working with files', views: 85 },
];
 
console.table(posts);
console.error('This message goes to the error stream');
 
console.time('sorting');
posts.sort((a, b) => b.views - a.views);
console.timeEnd('sorting');

console.table() draws a table in the terminal with the columns id, title and views. console.time() and console.timeEnd() with the same label measure the time between them, for example "sorting: 0.05ms".

Nested objects

console.log() in Node.js shows nesting only down to the third level; deeper it prints [Object]. To see everything, use console.dir() with the depth option:

// app.js
const post = { id: 1, author: { name: 'Anna', profile: { city: { name: 'Berlin' } } } };
 
console.dir(post, { depth: null });

depth: null removes the limit, and the terminal shows name: 'Berlin'.

Running under the debugger

The --inspect flag turns on the debugger. Add a debugger line to the code where you want to stop:

// src/posts.js
export async function addPost(title, body) {
  const posts = await loadPosts();
  debugger;
  // ...
}

Start the server with --inspect:

node --inspect src/server.js

Open chrome://inspect in Chrome and click inspect under your script. Send a POST request to /posts — the program stops at the debugger line, and the panel shows title, body and posts. The --inspect-brk flag stops the program right at the first line.

Debugging in VS Code

In VS Code the easiest way is to open a terminal with the "JavaScript Debug Terminal" command from the command palette (Ctrl+Shift+P). Any program started in it with node or npm run connects to the debugger right away. A breakpoint is set by clicking to the left of the line number — no debugger line is needed.

Key in VS CodeAction
F5Continue to the next breakpoint
F10Next line
F11Step into a function
Shift+F5Stop debugging

Common mistake

debugger lines and temporary console.log() calls are easy to leave in the code. On a server without a debugger, debugger does nothing, but stray messages clutter the log and may print passwords or personal data. Before committing, find them with a project-wide search and remove them.

Thanks for reading!

Donate to the site — we work hard for you.