欲善其事,先利其器。Nodejs调试方法主要可以分为三类:
- core node.js debugger:无用户接口,简陋,一般不用
- 基于chome的node-inspector
- IDE(如webstorm、phpsotrm)插件
以一个小demo(hello.js)为例对后面两者做介绍:
var http = require('http');
var url = require('url');
http
.createServer(function (req, res) {
var path = url.parse(req.url).pathname;
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(path);
})
.listen(1337, "127.0.0.1");
console.log('Server running at http://127.0.0.1:1337/');
Node-inspector
- npm安装node-inspector包:
npm install -g node-inspector - 后台进程的方式启动:
node-inspector &
注意:这样默认是以8080端口启动,该端口经常被apache、nginx等常用web服务占用而报错,错误内容如下:
➜ demo1 Node Inspector v0.12.8
Cannot start the server at 0.0.0.0:8080. Error: listen EADDRINUSE 0.0.0.0:8080.
There is another process already listening at this address.
Run `node-inspector --web-port={port}` to use a different port.
[1] + 27585 done node-inspector
这时可以以–web-port=[port]的方式指定其他端口,方式为:
node-inspector & --web-port=8008
- 启动node运行程序:
node --debug hello.js
或者
node --debug-brk hello.js
- 浏览器窗口输入如下
http://127.0.0.1:8008/?port=5858
- u will get hello.js in chrome window
大致说明
- –debug & –debug-brk的区别:
–debug会运行在请求文件后立即用node执行该文件;
–debug-brk会在文件第一行设中断,是否继续执行需要依据用户在chrome下的调试命令; - chrome监听端口8008请求后,通知node-inspector(5858端口:可通过–debug-port[port]进行配置),最终基于NodeJS 提供的内建调试模块进行调试