1、js文件编码
utf-8无bom编码
2、服务端脚本程序入口 (main())
http.createServer(function(req, res) {
var handler = UrlMap[url.parse(req.url).pathname] || notFound;
handler(req, res);
}).listen(8080);
3、UrlMap,保存请求的路径和对应的处理,通过setUrlMap来设置
var UrlMap = {};
setUrlMap = function (path, handler) {
UrlMap[path] = handler;
};
4、notFound,未定义的请求,作为静态文件来访问,文件不存在则返回404
notFound = function (req, res) {
var uri = url.parse(req.url).pathname;
var filename = path.join(process.cwd(), uri);
path.exists(filename, function(exists) {
if(!exists) {
res.writeHead(404, {"Content-Type": "text/plain"});
res.end("404 Not Found\n");
return;
}
fs.readFile(filename, "binary", function(err, file) {
if(err) {
res.writeHead(500, {"Content-Type": "text/plain"});
res.end(err + "\n");
return;
}
res.writeHead(200);
res.end(file, "binary");
});
});
}