What is Node.js?
Node.js lets you run JavaScript on a server, not only in a browser. A bug is a mistake in a program. Debugging is the work of hunting the bug down, like a detective looking for clues.
Method 1: console.log
The simplest way is to print values while the program runs.
- Open your file, for example
app.js. - Add a line where you want to look:
console.log('user value:', user);
This prints the value of user in the terminal.
- Run the program:
node app.js
This starts your app and shows the printed lines.
- Read the output. Check if values look as you expect.
- Remove the extra lines when you finish.
Method 2: Read the error message
When Node.js crashes, it prints an error and a stack trace. This is a list of the steps that led to the crash. The first lines tell you the file name and line number. Open that file and look at that line first.
Method 3: The built-in inspector
- Start your app in inspect mode:
node --inspect-brk app.js
This starts the app and pauses on the first line, waiting for a debugger.
- Open Google Chrome and type
chrome://inspectin the address bar. - Click inspect under your app.
- Click in the line numbers to set a breakpoint. A breakpoint is a stop sign that pauses the code on that line.
- Press the play button to run until the next stop.
- Look at the variables in the side panel. Use the step buttons to move one line at a time.
Method 4: Use VS Code
- Open your folder in Visual Studio Code.
- Click the line number to place a breakpoint.
- Press F5 and choose Node.js.
- Watch the variables and step through the code.
On a hosting server
Look at the log files. Your app may write errors to a file such as stderr.log or to the output of your process manager. If you use PM2, run pm2 logs to see the output. This shows the latest lines from your app.
If you need help with your hosting setup, open a support ticket.
Quick recap
- Use
console.logfor quick checks. - Read the stack trace to find the file and line.
- Use
node --inspect-brkwith Chrome or VS Code for step-by-step debugging. - Check server logs when the app runs online.