In case you are using node to run javascript on command line, you can use Chrome to debug javascript. It support GUI debugger functionalities like adding break point, stepping over a line etc. This can be helpful to understand existing code also. Here are steps to debug javascript code using node-inspector, node-debug, nodemon and Chrome on Mac.
Install/update node
To install node use the following commands:
$ brew update $ brew install node
If you need to upgrade node, use the following commands:
$ brew update $ brew upgrade node $ node -v v5.1.0 $npm -v 3.4.1
Install node-inspector, node-debug, nodemon
Install node-inspector, node-debug and nodemon using the following commands:
$ sudo npm install -g node-inspector $ sudo npm install -g nodemon
Note that node-debug is part of node-inspector itself. You should not install it separately.
Create test javascript for debugging
Create a test javascript file hello.js which can be used for debugging. Write the following code in it:
var x = 1; var y = 2; var s = x + y; console.log("sum=" + s + "\n"); console.log("Done\n");
Run node-inspector
Run node-inspector in background. It will start a webserver on port 8080.
$ node-inspector & Visit http://127.0.0.1:8080/?ws=127.0.0.1:8080&port=5858 to start debugging.
You can also run node-inspector on a specific port using –web-port argument as shown below:
$ node-inspector --web-port 8080 &
Run node-debug
Run node-debug to debug hello.js as shown below:
$ node-debug hello.js
It will automatically open http://127.0.0.1:8080/?ws=127.0.0.1:8080&port=5858 in Chrome browser. It will start the debugger stopped at the first line in hello.js. You can create desired break points in javascript code, etc. as shown below:
Use nodemon to watch changes
In case you need to make frequent changes to hello.js, you can use nodemon to debug. It will automatically reload the new hello.js whenever there is a change.
$ nodemon --debug-brk hello.js
By using –debug-brk (instead of –debug) we are telling nodemon to break at first line. After running this command open url http://127.0.0.1:8080/?ws=127.0.0.1:8080&port=5858 in Chrome browser and start debugging.