Node.js调试技巧

1. console.log

跟前端调试相同,通过一步步打印相关变量进行代码调试

2. 使用Node.js内置的调试器

通过node debug xxx.js来进行调试:

[root@~/wade/nodejs/professional-nodejs/chapter18]# node debug app_with_bug.js help Commands: run (r), cont (c), next (n), step (s), out (o), backtrace (bt), setBreakpoint (sb), clearBreakpoint (cb), watch, unwatch, watchers, repl, restart, kill, list, scripts, breakOnException, breakpoints, version

3. 使用Node Inspector来进行调试

1). 安装

npm install -g node-inspector

2). 启动Node Inspector(默认监听8080端口)

[root@~/wade/nodejs/professional-nodejs/chapter18]# node-inspector Node Inspector v0.7.4 Visit http://127.0.0.1:8080/debug?port=5858 to start debugging.

3). 运行应用程序(通过

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

实现:

var path = require('path'), fs = require('fs'); require('http').createServer(function(req, res) { // 解析文件路径,默认以当前目录为根目录查找文件 // 这里可以通过配置root值来做为相对根目录查找文件 var file = path.normalize('.' + req.url); console.log('Trying to serve', file); function reportError(err) { console.log(err); res.writeHead(500); res.end('Internal Server Error'); } // 判断文件是否存在 path.exists(file, function(exists) { // 文件存在,则读取文件流,输出 if (exists) { fs.stat(file, function(err, stat) { var rs; if (err) { return reportError(err); } if (stat.isDirectory()) { res.writeHead(403); res.end('Forbidden'); } else { rs = fs.createReadStream(file); rs.on('error', reportError); res.writeHead(200); rs.pipe(res); } }); // 404 } else { res.writeHead(404); res.end('Not found'); } }); }).listen(4000);

完整源码:https://github.com/billfeller/professional-nodejs/tree/master/chapter11

参考:

Chapter11 Building HTTP Servers

最后:

以上只是一个实现静态服务器的示例,生产应用仍然首选Nginx。

原文地址:https://www.cnblogs.com/2881064178dinfeng/p/7099825.html