index.js
根據請求的路徑pathname,返回響應的頁面。
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(3000);
// 控制台會輸出以下信息
console.log('Server running at http://127.0.0.1:3000/');
index.html
<html> <head> <title>Sample Page</title> </head> <body> Hello World! </body> </html>
瀏覽器中打開: http://127.0.0.1:3000/index.html
頁面顯示 index.html
