response.write(file, "binary");
response.end();
}
});
}
exports.start = start;
exports.upload = upload;
exports.show = show;
router.js
function route(handle, pathname, response, request) {
console.log("About to route a request for " + pathname);
if (typeof handle[pathname] === 'function') {
handle[pathname](response, request);
} else {
console.log("No request handler found for " + pathname);
response.writeHead(404, {"Content-Type": "text/html"});
response.write("404 Not found");
response.end();
}
}
exports.route = route;result:



知识点:
其中用到了fs模块的readFile读取文件,它有同步和异步两个版本。node.js中,并不是所有的API都提供了异步和同步版本,node.js不鼓励使用同步I/O。
//this is async 异步
/*
fs.readFile调用时所做的工作只是将异步式I/O请求发送给了操作系统,然后立即返回并执行后面的语句,执行完以后进入事件循环监听事件。
当fs接收到I/O请求完成的事件时,事件循环会主动调用回调函数以完成后续工作。
*/
var fs = require('fs');
fs.readFile('file.txt', 'utf-8', function(err, data){
if (err){
console.error(err);
} else {
console.log(data);
}
});
//this is sync 同步
var fs = require('fs');
var data = fs.readFileSync('file.txt', 'utf-8');
console.log(data);
console.log('end.');希望本文所述对大家nodejs程序设计有所帮助。









