Skip to content

Instantly share code, notes, and snippets.

@plembo
Last active June 18, 2021 18:11
Show Gist options
  • Save plembo/b35d934def46c4fb2d890a82e981d9c6 to your computer and use it in GitHub Desktop.
Save plembo/b35d934def46c4fb2d890a82e981d9c6 to your computer and use it in GitHub Desktop.
Debugging in Node.js

Debugging in Node.js

Notes from Andrew Mead, The Complete Node.js Developer Course, Udemy, 2018.

https://www.udemy.com/the-complete-nodejs-developer-course-2/learn/v4/overview

Two techniques: command line and Chrome Dev Tools.

Command line:

node inspect debugging.js

Opens the debugger:

< Debugger listening on ws://127.0.0.1:9229/588da449-527f-45f5-af20-1c5ebbdc104f
< For help see https://nodejs.org/en/docs/inspector
< Debugger attached.
Break on start in debugging.js:1
> 1 (function (exports, require, module, __filename, __dirname) { var person = {
  2     name: 'Andrew'
  3 };
debug>

Can use "list" with a number to list any number of lines:

debug> list(10)

Prints 10 lines.

Run "n" to step into next statement.

Run "c" to continue to end.

Exit by doing control-c twice.

Use "repl" (Read Evaluate Print Loop) to explore values, etc.

debug> repl

Can access anything you want, add statements, redefine variables, etc.

person.age = 100

Exit with control-c.

Can set breakpoints by adding debugger statement at the place you want to stop inside script.

debugger;

With this in place, typing "c" will take you to that breakpoint.

Check values using "repl".

Example of debugging more complicated program using first course project (notes app):

node inspect app.js read --title="to buy"

Dedicated Chrome DevTools for Node

Run script using "" command

node --inspect-brk playground/debugging.js

Open Chrome browser, type "chrome://inspect" in the address bar and check to see that your script is listed under Remote Target.

Do not click on "inspect" link under script listing. Instead, click on "Open dedicated DevTools for Node" just above the Remote Target heading.

You should see multiple panels of Developer Tools. Counter-clockwise from left to right: Network/Filesystem, Console, status. In the middle will be an editor window holding the text of the script being debugged.

Blue button on upper right hand corner will play the script. It will stop at any breakpoints set in the script using the "debugger" statement. You can also set breakpoints by clicking on a line number along the left margin of the editor window.

Use nodemon to automatically reload after each change:

nodemon --inspect-brk playground/debugging.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment