No matter how good your code is, bugs will always show up. Debugging is a crucial skill for every developer, and Node.js provides multiple ways to find and fix errors quickly.
In this post, I’ll share 5 simple debugging techniques that every beginner should know, along with code examples to help you understand them better.
Let’s dive in! 🚀
1. Use console.log()
Wisely
The easiest way to debug is by using console.log()
. You can print variables at different points in your code to see what’s happening.
Example:
function add(a, b) {
console.log('a:', a, 'b:', b); // Check input values
return a + b;
}
console.log(add(5, 10)); // Expected output: 15
💡 Tip: Avoid leaving unnecessary console.log()
statements in your production code. They can clutter your logs and slow down performance.
2. Use the Node.js Debugger
Node.js comes with a built-in debugger that allows you to pause execution and inspect variables step by step.
How to use:
- Add debugger; in your code.
- Run the script with
node --inspect index.js
. - Open Chrome, go to
chrome://inspect
, and start debugging.
Example:
function multiply(x, y) {
debugger; // The debugger will pause here
return x * y;
}
console.log(multiply(3, 4)); // Run this with node --inspect
This method helps you step through the code and inspect variables in real time.
3. Use Breakpoints in VS Code
Instead of adding multiple console.log()
statements, you can use breakpoints in VS Code to pause execution and inspect variables.
How to use:
- Open your JavaScript file in VS Code.
- Click on the left side of the line number to add a breakpoint.
- Press
F5
(or select “Run & Debug”) to start debugging.
Example:
function greet(name) {
return `Hello, ${name}!`;
}
console.log(greet("Alice")); // Add a breakpoint here in VS Code
When you run the debugger, the execution will pause at the breakpoint, allowing you to inspect variable values.
4. Handle Errors Properly (try…catch)
Ignoring errors can make debugging harder. Always use try...catch
to handle potential issues, especially in async functions.
Example:
async function fetchData() {
try {
let response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
let data = await response.json();
console.log(data);
} catch (error) {
console.error("Error fetching data:", error.message);
}
}
fetchData();
Using try...catch
ensures that if something goes wrong (like a network failure), the error is caught and logged properly.
5. Read Logs and Stack Traces Carefully
When an error appears in Node.js, don’t panic! The stack trace tells you exactly where the issue is.
Example:
function divide(a, b) {
if (b === 0) throw new Error("Cannot divide by zero!");
return a / b;
}
console.log(divide(10, 0)); // This will throw an error
Error Output:
Error: Cannot divide by zero!
at divide (index.js:2:19)
at Object.<anonymous> (index.js:5:13)
The stack trace shows:
- The error message (Cannot divide by zero!)
- The function where it happened (divide)
- The exact file and line number (index.js:2:19)
Reading stack traces carefully can save you hours of debugging!
Conclusion
Debugging is an essential skill for every Node.js developer. Here’s a quick recap of the 5 techniques we covered:
✅ Use console.log() wisely – Print values to check what’s happening.
✅ Use the Node.js Debugger – Step through code using node --inspect.
✅ Use breakpoints in VS Code – A cleaner way to debug without console spam.
✅ Handle errors properly – Use try…catch to catch unexpected issues.
✅ Read logs and stack traces – Error messages guide you to the problem.
The more you practice these techniques, the better you’ll get at finding and fixing bugs!
#Nodejs #Debugging #JavaScript #WebDevelopment #CodingTips
Comments
Please login to publish your comment!
By logging in, you agree to our Terms of Service and Privacy Policy.
No comments here!