4 min read
•Question 41 of 62mediumHow to debug Node.js applications?
Debugging techniques and tools.
What You'll Learn
- Built-in debugger
- Chrome DevTools
- VS Code debugging
Chrome DevTools
$ terminalBash
node --inspect app.js
# or break on first line
node --inspect-brk app.jsOpen chrome://inspect in Chrome.
VS Code Debugging
data.jsonJSON
// .vscode/launch.json
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${workspaceFolder}/app.js",
"env": {
"NODE_ENV": "development"
}
},
{
"type": "node",
"request": "attach",
"name": "Attach",
"port": 9229
}
]
}Console Methods
code.jsJavaScript
// Beyond console.log
console.table([{ a: 1, b: 2 }, { a: 3, b: 4 }]);
console.time('operation');
// ... operation
console.timeEnd('operation');
console.trace('Trace:');
console.dir(obj, { depth: null });
// Debug module
const debug = require('debug')('app:server');
debug('Server starting...');
// DEBUG=app:* node app.jsDebugging Async Code
code.jsJavaScript
// Async stack traces
node --async-stack-traces app.js
// Or use Error.captureStackTrace
function debugAsync(fn) {
const stack = {};
Error.captureStackTrace(stack);
return async (...args) => {
try {
return await fn(...args);
} catch (err) {
err.stack += '\nAsync stack:\n' + stack.stack;
throw err;
}
};
}