如何调试NodeJS
我终于要不能忍受CSDN这个垃圾网站的blog了,于是乎我决定借着学习nodejs的机会自己搭建一个blog,并且将其部署到cloudfoundry上。于是乎我将陆续完成下面的系列文章。所以文章里面的代码都是这个blog的实现。
Sure it's important to debug for any programming language, and it should be learnt at first time to use a new language. I forgot why I put this debug blog at the end of the serials blogs. No matter what's the reason, now we need to introduce how to debug nodejs. This article has two parts, one is the native debugger for nodejs, and another one is Node Inspector. In fact there is the third way to debug nodejs, based on Eclipse, which is not introduced here, but you can find more introduction from here: Using Eclipse as Node Applications Debugger.
Prepare to debug Have below simple code as our sample, name it as 'debug.js'.
var count = 10;var sum = 0;debugger;for (var i = 1; i < count; i++) { sum += i;}console.log(sum);
Note we have debugger;
at line 3, which means we put a breakpoint here. Actually it's the same with the normal Javascript running in browser Chrome, in which put a debugger;
statement. The difference it we add this statement into js code running in browser to force the execution to pause at load time. But in to debug nodejs, it's not necessary, because in debug mode the execution is always paused at first line.
。。。。。。
Finally we finish the basic commands of built-in debugger. Now we introduce a debug tool with UI, Chrome. You know nodejs is built on V8 js engine, which is the engine for Chrome browser, therefore it's a good idea to use Chrome as debug tool.
Setup debug
To use node-inspector we need change our sample code as below, which is from node-inspector test code, name it as 'debug.js' too.
var http = require('http');var x = 0;http.createServer(function (req, res) { x += 1; res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello World ' + x);}).listen(8124);console.log('Server running at http://127.0.0.1:8124/');
Node Inspector only supports nodejs HttpServer, therefore we cannot debug previous sample code in before section, If we want to debug that code, we need wrap it into a http server like above sample code.
。。。。。。