Node.js是服務端編程的終極武器,小白們不得不服


服務端編程走過PHP,JAVA,C#,感覺都很笨重,使用起來學習成本高,調試起來也非常困難。業務時間學習了一點Node.js,這是將Javascript用於服務端編程的一種技術,頓感天空晴朗,小白們不妨來試一試。

先看一段 index.js 代碼,這是處理客戶端http請求的,從語法上看與javascript一模一樣,會前端開發的人都會寫,但它實現的卻是服務端的功能,自此前端程序員可以統治一切了 ,無需再受後端的氣了。

<code>authentication = function(req, res, next) {
var body, currentUserId, i, len, ref, reqPath, userAgent;
userAgent = req.get('user-agent').substr(0, 50);
console.log("authentication, userAgent = " + userAgent + ", path = " + req.path);
ref = ['/misc/demo_square', '/misc/latest_update', '/user/verify_code_yp_t', '/misc/client_version', '/misc/mobile_version', '/user/login', '/user/register', '/user/reset_password', '/user/send_code', '/user/send_code_yp', '/user/verify_code', '/user/verify_code_yp', '/user/delete', '/user/get_sms_img_code', '/user/check_username_available', '/user/check_phone_available', '/user/regionlist', '/ping'];
for (i = 0, len = ref.length; i < len; i++) {
reqPath = ref[i];
if (req.path === reqPath) {
console.log("authentication, reqPath = " + reqPath);
if (req.body.password) {
body = JSON.stringify(req.body).replace(/"password":".*?"/, '"password":"**********"');
} else {
body = JSON.stringify(req.body);
}
console.log("authentication, body = " + body);
Utility.logPath('%s %s %s %s', userAgent, req.method, req.originalUrl, body);
return next();
}
}
currentUserId = Session.getCurrentUserId(req);
if (!currentUserId) {
console.log("currentUserId Not loged in.");
return res.status(403).send('Not loged in.');
}
console.log("currentUserId = " + currentUserId);
Utility.logPath('%s User(%s/%s) %s %s %s', userAgent, Utility.encodeId(currentUserId), currentUserId, req.method, req.originalUrl, JSON.stringify(req.body));
return next();
};

/<code>

Node.js 有log打印功能,可以直接在控制檯根據log查看代碼運行邏輯,方便開發調試。

console.log("authentication, body = " + body);

更為方便的是你部署在雲端的Node.js代碼,可以用Chrome瀏覽器在客戶端進行斷點調試,無需任何IDE工具,只需要安裝inspect插件即可:


Node.js是服務端編程的終極武器,小白們不得不服

inspect插件

有沒有那種服務端語言有這麼方便?除了Node.js沒有別的了。Javascript的生命力真是頑強,十幾年不斷的進化和變種,生存的越來越好了


分享到:


相關文章: