node.js--web服務器
目前最主流的三個Web服務器是Apache
、Nginx
、IIS
。
使用 Node 建立 Web 服務器
如下是演示一個最基本的 HTTP 服務器架構(使用8081端口),建立 server.js 文件,代碼以下所示:
var http = require('http');
var fs = require('fs');
var url = require('url');
// 建立服務器
http.createServer( function (request, response) {
// 解析請求,包括文件名
var pathname = url.parse(request.url).pathname;
// 輸出請求的文件名
console.log("Request for " + pathname + " received.");
// 從文件系統中讀取請求的文件內容
fs.readFile(pathname.substr(1), function (err, data) {
if (err) {
console.log(err);
// HTTP 狀態碼: 404 : NOT FOUND
// Content Type: text/plain
response.writeHead(404, {'Content-Type': 'text/html'});
}else{
// HTTP 狀態碼: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/html'});
// 響應文件內容
response.write(data.toString());
}
// 發送響應數據
response.end();
});
}).listen(8081);
// 控制檯會輸出如下信息
console.log('Server running at http://127.0.0.1:8081/');
接下來咱們在該目錄下建立一個 text.htm 文件,代碼以下:
<html>
<title></title>
<meta></meta>
<body>
<h3>hello welcome</h3>
</body>
</html>
執行 server.js 文件:
$ node server.js
Server running at http://127.0.0.1:8081/
結果以下:

其中server.js的讀取文件代碼須要注意一下:
fs.readFile(pathname.substr(1), function (err, data{})
pathname的輸出值是/text.html
pathname.substr(1)指的就是text.html