版權聲明:本文為部落客chszs的原創文章,未經部落客允許不得轉載。 https://blog.csdn.net/chszs/article/details/8915944
Node.js開發手冊(一)
作者:chszs,轉載需注明。部落格首頁:
http://blog.csdn.net/chszs一、Node.js簡介
Node.js由于其簡潔性而受到廣泛關注。與PHP或ASP不同,後者在Web伺服器和代碼間沒有間隔,也不需要自定義大量的配置檔案。使用Node.js,我們可以建立伺服器,自定義它,在代碼層傳遞所有的内容。
二、建構路由器
為了傳遞Web内容,我們需要使URI有效。為了使得開發效率更高,這裡我向大家推薦兩款工具,它可以幫助Node.js程式在改動後自動部署生效,簡化了開發。工具如下:
1. Hotnode
Hotnode是一個包,可以讓代碼在修改儲存後實作自動重載。其特征有兩點:
一是當檔案發生改變後,自動重載Node.js代碼。
二是會檢測目前目錄及其子目錄。
2. Supervisor
node-supervisor也是一個包,它可以運作Node.js程式,觀察代碼的變動情況,自動重新熱部署,無需擔心記憶體洩漏以及中間子產品引用的清除等。
Hotnode和Supervisor兩者的功能差不多,不過Hotnode先于Supervisor差不多一年釋出。
兩者的安裝都很簡單,以supervisor為例,安裝如下:
$ sudo npm install supervisor -g
三、測試
編寫一個Node.js程式,名為server.js,内容如下:
// server.js
var http = require('http');
http.createServer(function(req, res){
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Woohoo!');
}).listen(8080);
用supervisor執行此程式,指令為:
$ supervisor server.js
用浏覽器通路位址:http://localhost:8080/
會顯示Woohoo!
四、修改代碼
我們可以使用path子產品提取路徑的基本名字,用decodeURI在用戶端解碼任何URI編碼。内容如下:
// server.js
var http = require('http');
var path = require('path');
var pages = [
{route: '', output:'Woohoo!'},
{route: 'about', output:'A simple routing with Node example'},
{route: 'another page', output: function(){return 'Here\'s ' + this.route;}},
];
http.createServer(function(req, res){
var lookup = path.basename(decodeURI(req.url));
pages.forEach(function(page){
if(page.route===lookup){
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(typeof page.output === 'function' ? page.output() : page.output);
}
});
if(!res.finished){
res.writeHead(404);
res.end('Page Not Found!');
}
}).listen(8080);
在終端上可以看到,代碼是實時被supervisor熱部署了的。
在浏覽器通路http://localhost:8080/aboutasd
會提示:Page Not Found!
在浏覽器通路http://localhost:8080/about
會提示:A simple routing with Node example