由於不做php相關的東西,懶得裝apache,乾脆利用nodejs搭建一個本地的伺服器用於測試。
nodejs這玩意兒吧,對做前端的介入後端簡直就是一把利器。而且目前,nodejs也越來越有商用價值。
nodejs其實是非常底層的,從功能上說,它既是apache也是php。像搭建http伺服器這種功能,本來是apache已經封裝好的,但nodejs需要我們手動來搭建。其實在實際應用中,我們可以使用現成的架構。但這裡,我想手動搭建,也加深一下對http伺服器的理解。
我們node執行下面這個檔案,我命名為http.js,它將建立一個httpServer並監聽3000連接埠。
var PORT = 3000;var http = require('http');var url=require('url');var fs=require('fs');var mine=require('./mine').types;var path=require('path');var server = http.createServer(function (request, response) { var pathname = url.parse(request.url).pathname; var realPath = path.join("assets", pathname); //console.log(realPath); var ext = path.extname(realPath); ext = ext ? ext.slice(1) : 'unknown'; fs.exists(realPath, function (exists) { if (!exists) { response.writeHead(404, { 'Content-Type': 'text/plain' }); response.write("This request URL " + pathname + " was not found on this server."); response.end(); } else { fs.readFile(realPath, "binary", function (err, file) { if (err) { response.writeHead(500, { 'Content-Type': 'text/plain' }); response.end(err); } else { var contentType = mine[ext] || "text/plain"; response.writeHead(200, { 'Content-Type': contentType }); response.write(file, "binary"); response.end(); } }); } });});server.listen(PORT);console.log("Server runing at port: " + PORT + ".");
上面我們還引入了一個mine.js,這是我自己寫的,裡面儲存的是名值對,用於定義不同尾碼的檔案所對應的返回方式:
exports.types = { "css": "text/css", "gif": "image/gif", "html": "text/html", "ico": "image/x-icon", "jpeg": "image/jpeg", "jpg": "image/jpeg", "js": "text/javascript", "json": "application/json", "pdf": "application/pdf", "png": "image/png", "svg": "image/svg+xml", "swf": "application/x-shockwave-flash", "tiff": "image/tiff", "txt": "text/plain", "wav": "audio/x-wav", "wma": "audio/x-ms-wma", "wmv": "video/x-ms-wmv", "xml": "text/xml"};
fs模組是用於讀取檔案的,提供讀取檔案的方法,其實仔細研究文檔會發現,它有同步和非同步兩種讀取方式。fs.exists這個方法網上很多文章寫作path.exists,,現在推薦寫作fs.exists這個方法。否則會警示:
需要注意的是,不僅瀏覽器訪問html檔案會形成一次訪問,裡面連結的js,css等外部檔案也會分別形成一次http訪問。所以,http.createServer的回調其實是在一次頁面訪問中執行了多次的。我們console.log(realPath)一下就可以看到:
這裡並沒有加入預設訪問index.html的功能,所以訪問地址要寫全http://127.0.0.1:3000/index.html