How to debug node js app with breakpoints and everything?
-
22-06-2021 - |
Question
I've installed node-inspector just to find out that it doesn't support breakpoints :| What's the point in it at all, bearing in mind that on big part node code is asynchronous and you simply cannot follow it step by step?..
I'm definitely missing a point here...
Anyway to debug node code with breakpoints and everything?
La solution
(For Node 8 and later)
Node.js has a built-in debugger. Normally you can turn on the debugger in two ways:
Start your Node.js app or script with the
--inspect
or--inspect-brk
switch. For example:$ node.js --inspect index.js
(Note: --inspect-brk
breaks before user code starts)
If for some reason you cannot start your Node.js app or script with the
--inspect
switch, you can still instruct the Node.js process to start listening for debugging messages by signalling it with SIGUSR1 (on Linux and OS X). For Node 8 and later it will activate the Inspector API, same as the --inspect switch$ kill -sigusr1 23485
(Note: you need to replace 23485 with your own Node.js process ID)
With the debugger turned on, you can open the Google Chrome browser, and type in the address bar chrome://inspect
Then you should see an entry listed under "Remote Target". Go ahead and click "inspect".
Now you can set breakpoints and start debugging your code.
Reference:
- https://nodejs.org/en/docs/guides/debugging-getting-started/
- Related issue on stackoverflow: Chrome Devtools Dedicated Node.js Inspector not stopping at breakpoints
Autres conseils
yupp, I've successfully used node-inspector. If you want permanent breakpoints, simply insert debugger;
in your code. See http://nodejs.org/api/debugger.html.
Making node wait until a debugger is attached, using node --inspect-brk script.js
(previously node --debug-brk script.js
), can also be very helpful.
To Debug a Node js application, one can use the debug inbuilt module
Insert debugger;
statement where you want to insert breakpoints
Run the file with command node inspect index.js
Press C to continue to next breakpoint
you can even debug values associated to variables at that breakpoint by typing repl
For more information, Please Refer https://nodejs.org/api/debugger.html
Have you tried using nodemon
library? it can be found here.
For development purposes you could start the app running nodemon. I have this script:
"dev": "nodemon --inspect src/index.js"
It will break any time a debugger
statement is reached in the code. To open the console where you can see the server code, open the console in chrome and click on the nodejs icon:
It also helps you refreshing the server every time you save any file on the server.
Let me know if it works!
Just to elaborate a bit here:
Set a debugger wherever you want the breakpoints to be and then run your code with node debug script.js/index.js
When the debugger stops at you breakpoint, you will need to repl to inspect the variables.