One of the best thing about node is that it can be debugged via the Remote Debugging Protocol. Here I would like to show a demo about how to setup a simple debuggable project.
Some requirements of this tutorial:
- Unix-like system environment.
- Some basic knowledge of node, npm and express.
- Some basic knowledge of shell.
You just need to create two files to make it work. First of all create a folder, let’s call it “debug_demo”.
$ mkdir debug_demo
Then the “package.json” file:
1 2 3 4 5 6 7 8 9 10 11 |
{ "name": "DebugDemo", "version": "0.0.1", "scripts": { "test": "node --debug app.js & node node_modules/.bin/node-inspector" }, "dependencies": { "express": "*", "node-inspector": "*" } } |
The “package.json” file is most important part of this project. There’s a package called “node-inspector” in the dependency section. It will setup a debug server for us to help exchange information between the node project and browser.
At last create the main file “app.js”:
1 2 3 4 5 6 7 8 9 10 |
var express = require('express'); var app = express(); app.all('*', function (req, res) { var s = req.originalUrl; res.send(s); console.log(s); }); app.listen(8112); |
Then, we need to run some commands in the shell:
1 2 3 4 |
$ npm install # ... $ npm test # ... |
Finally open your browser and visit the port 8112 and 8080, you can change the default port if it is already in use. To you it may be “http://127.0.0.0:8112/” and “http://127.0.0.0:8080/“. The result should like below:
Very simple, isn’t it?