第一次用node.js写 第一次玩mangoDB 第一次使用文件 优化空间很大。。谢谢观赏 :http://callme.cnodejs.net/
js代码:
var http = require('http'),
db = require('./config').db;
fs = require('fs');
var path = "html/index.html";
http.createServer(function(req, res){
fs.readFile(path, "binary", function(err, file) {
if(err) {
res.writeHead(200, {"Content-Type": "text/plain"});
res.write(path+" Not Found\n");
res.end();
return;
}
res.writeHead(200, {"content-type":"text/html;charset=utf8"});
res.write(file, "binary");
showCount(res,1);
});
}).listen(80);
console.log("server started at port 80");
function showCount(res,layer){
if (layer>3){
console.log("DB Init failed");
res.end("
悲剧...计数器初始化失败...</body></html>");
}
if (!dbconn){
var dbconn = db.collection("RequestCount");
console.log("Connect to 'RequestCount'");
}
dbconn.findOne({name:"counter"}, function (err, data) {
if (err) {
console.log("findOne {name:\"counter\"} failed-> DB try Init..");
dbconn.save({name:"counter", count:0}, function (err) {
if (err) {
console.log("save {name:\"counter\", count:1} failed -> DB try Init..");
}
console.log("DB try Init Successed!");
showCount(res, layer + 1);
})
} else {
if (!data){
console.log("data is null -> DB try Init..");
dbconn.save({name:"counter", count:0}, function (err) {
if (err) {
console.log("save {name:\"counter\", count:1} failed -> DB try Init..");
}
console.log("DB try Init Successed!");
showCount(res, layer + 1);
})
}
var newcount = data.count + 1;
console.log("Count update to" + newcount);
dbconn.update(
{name:"counter"},
{$set:{count:newcount}},
function (err) {
if (err) {
console.log("DB update failed");
showCount(res, layer + 1);
}
}
)
res.end("
您是获得了第" + newcount + "次请求的围观群众.</body></html>");
}
});
}
That‘s all 欢迎拍砖。。。。
4 回复