node.js在本地搭建web伺服器
學習筆記--node.js搭建web伺服器
以下是一個本地web伺服器搭建案例,記為學習筆記,以便日後有需要時檢視。
我們採用node.js搭建,所以事先肯定需要安裝node.js。前往官網安裝即可,安裝好後可以使用cmd輸入命令node -v來檢測安裝是否成功。如果安裝成功了,那麼會顯示node.js的版本號
我們接下來的javascript程式碼會在node.js環境中執行,所以只有將node.js安裝好,才能成功啟動服務。
建立js檔案,在js檔案中編寫如下程式碼:
var http = require('http'); var url = require('url'); var path = require('path'); var fs = require('fs'); var dir, arg = process.argv[2] || ''; // 命令列第三個引數,用來接收目錄,可為空,相對當前server.js檔案的目錄名稱 // 比如使用命令 node server debug,意思就是debug資料夾與server.js檔案同級 // 且你想以debug資料夾啟動web服務 http.createServer(function (req, res) { var pathname = __dirname + url.parse(req.url).pathname; dir = dir ? dir : pathname; // 記住dir(目錄) pathname = dir ? pathname.replace(dir, dir + arg + '/') : pathname; // 替換檔案靜態路徑 if (path.extname(pathname) == "") { pathname += "/"; } if (pathname.charAt(pathname.length - 1) == "/") { pathname += "test.html"; // 入口檔案,此處預設test.html } fs.exists(pathname, function (exists) { if (exists) { switch (path.extname(pathname)) { case ".html": res.writeHead(200, {"Content-Type": "text/html"}); break; case ".js": res.writeHead(200, {"Content-Type": "text/javascript"}); break; case ".css": res.writeHead(200, {"Content-Type": "text/css"}); break; case ".gif": res.writeHead(200, {"Content-Type": "image/gif"}); break; case ".jpg": res.writeHead(200, {"Content-Type": "image/jpeg"}); break; case ".png": res.writeHead(200, {"Content-Type": "image/png"}); break; default: res.writeHead(200, {"Content-Type": "application/octet-stream"}); } // res可以自己新增資訊來簡單互動 比如可以修改點header資訊 或者修改返回的資源資料 fs.readFile(pathname, function (err, data) { res.end(data); }); } else { res.writeHead(404, {"Content-Type": "text/html"}); res.end("<h1>404 Not Found</h1>"); } }); }).listen(8085, "127.0.0.5"); // 伺服器埠 console.log("server running at http://127.0.0.5:8085/");
這樣,一個js檔案就編寫好了,該js檔案命名為server.js,那麼我們在cmd中就使用如下命令啟動服務:node server
當出現server running at http://127.0.0.5:8085/時,服務就啟動成功了。
然後,我們建立一個html檔案:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <div>helloworld</div> </body> </html>
該html檔案起名為:test.html
起其他名字也是可以的,只不過要在上方js檔案中的pathname將檔名修改為你實際命名的html檔案。
將該html檔案放入和server.js在同個目錄中
最後在瀏覽器中輸入:127.0.0.5:8085即可訪問test.html檔案
到此,一個簡單又好玩的本地服務就搭好了,可以將自己做好的網頁放到上面演示,也是很不錯的體驗哦