Friday, March 29, 2013

Using Chrome Developer Tools to Debug node.js Applications

1. Install node.js
Visit http://nodejs.org/, download and install for your platform.

2. Install node-inspector
npm install node-inspector

Tip: "npm" is the node.js package manager; its path is added to the environment upon installation.

3. Write a script to be debugged, save as .js
Sample script:

// Script start
var APP_PORT = 8080;
var http = require('http');

var server = http.createServer(function(request, response) {
  response.writeHead(200);
  response.end('Hello, world!');
});
server.listen(APP_PORT, function(){
  console.log("Listening on http://localhost:" + APP_PORT);
});
// Script end

4. Start the node server in debugging mode; this will enable the debugger ("DEBUG_PORT") on port 5858
node --debug path/to/your/script.js

Tip: "node" is the core node.js server; its path is added to the environment upon installation.

5. Connect node-inspector to the node server, specifying a port ("INSPECT_PORT")
node-inspector --web-port=8989

Tip: Use "netstat -a -o" to see what ports are in use, before assigning INSPECT_PORT.

This puts three (3) ports into use:
APP_PORT (8080) - the port used by the application to respond to web requests.
DEBUG_PORT (5858) - the port used by node.js to serve up debugging requests.
INSPECT_PORT (8989) - the port used by node-inspector to relay requests to node.js' debugger.

6. Connect Chrome locally to the port served by node-inspector.

    http://127.0.0.1:INSPECT_PORT/debug?port=DEBUG_PORT

Once loaded, you'll get access to Chrome Developer Tools' Scripts and Console tabs, enabling you to breakpoint and inspect executing code, as well as view console output.

No comments:

Post a Comment