- Using a Debugger: The Node.js debugger can be started using the
--inspect
flag. This opens up a debugging port that you can connect to using a debugger client like VS Code or Chrome DevTools. Here's an example of how to use the Node.js debugger:
function add(a, b) { debugger; return a + b; }
const result = add(1, 2); console.log(result);
In this example, we're using the debugger
keyword to set a breakpoint in our code. When we run this code with the --inspect
flag and connect to it using a debugger client, we can step through the code and inspect variables to see what's happening.
- Using console.log: Sometimes, the simplest debugging tool is the best. The
console.log
function is a quick and easy way to output values to the console. Here's an example of how to useconsole.log
to debug a function:
function multiply(a, b) { console.log(Multiplying ${a} and ${b}); const result = a * b; console.log(Result is ${result}); return result; }
const result = multiply(2, 3); console.log(Final result is ${result});
In this example, we're using console.log
to output the values of a
and b
, as well as the result of the multiplication operation. This can help us see what's happening inside the function and make sure it's doing what we expect.
- Using the Node.js inspector: The Node.js inspector is a powerful tool that provides a range of debugging features. Here's an example of how to use the inspector to profile a function:
function fibonacci(n) { if (n <= 1) { return 1; }
return fibonacci(n - 1) + fibonacci(n - 2); }
const start = process.hrtime.bigint(); const result = fibonacci(40); const end = process.hrtime.bigint(); console.log(Result is ${result}); console.log(Took ${(end - start) / 1000000n} ms to run);
require('inspector').open(9229, '
localhost
', true);
In this example, we're using the Node.js inspector to profile our fibonacci
function. We're measuring the time it takes to run the function and outputting the result to the console. Then, we're using the require('inspector').open
method to open the inspector and analyze the performance of our function.
- Using a linter: A linter like ESLint can help catch errors and potential issues in your code. Here's an example of how to use ESLint to catch unused variables:
function add(a, b) { const unused = 'this variable is unused'; return a + b; }
const result = add(1, 2); console.log(result);
If we run this code through ESLint, we'll get a warning that the unused
variable is not being used:
1:10 warning 'unused' is assigned a value but never used no-unused-vars
This can help us catch errors and improve the quality of our code.
- Using breakpoints: Breakpoints can be set using the
debugger
keyword or through a debugger client like VS Code or Chrome DevTools. Here's an example of how to use a breakpoint in a Node.js app:
const express = require('express'); const app = express();
app.get('/', (req,