1. 程式人生 > >用node.js搭建一個靜態資源站 html,js,css正確加載 跳轉也完美實現!

用node.js搭建一個靜態資源站 html,js,css正確加載 跳轉也完美實現!

都在 加載 簡單 pipe tps color exec create 包含

昨天剛買了一個服務器想著用來測試一些自己的項目,由於是第一次建站,在tomcat,linux,node.js間想了好久最終因為node搭建比較方便沒那麽麻煩就決定用node.js來搭建網站項目。

搭建服務器也很簡單首先下載完安裝node.js後,建立一個項目文件夾在文件夾下建一個js文件可任意取名,這個文件對項目進行配置

"use strict";
//加載所需要的模塊
var http = require(‘http‘);
var url = require(‘url‘);
var fs = require(‘fs‘);
var path = require(‘path‘);
var cp = require(‘child_process‘);

//創建服務 var httpServer = http.createServer(processRequest); // 這是端口號 var port = 80; //指定一個監聽的接口 httpServer.listen(port, function() { console.log(`app is running at port:${port}`); console.log(`url: http://localhost:${port}`); cp.exec(`explorer http://localhost:${port}`, function () { }); }); //響應請求的函數
function processRequest (request, response) { //mime類型 var mime = { "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" }; //request裏面切出標識符字符串 var requestUrl = request.url; //url模塊的parse方法 接受一個字符串,返回一個url對象,切出來路徑 var pathName = url.parse(requestUrl).pathname; //對路徑解碼,防止中文亂碼 var pathName = decodeURI(pathName); //解決301重定向問題,如果pathname沒以/結尾,並且沒有擴展名 if (!pathName.endsWith(‘/‘) && path.extname(pathName) === ‘‘) { pathName += ‘/‘; var redirect = "http://" + request.headers.host + pathName; response.writeHead(301, { location: redirect }); //response.end方法用來回應完成後關閉本次對話,也可以寫入HTTP回應的具體內容。 response.end(); } //獲取資源文件的絕對路徑 /* var filePath = path.resolve(__dirname + pathName);*/ //__dirname是訪問項目靜態資源的路徑 我的項目靜態文件都在public下所以我寫public可根據自己項目路徑來配置哦 var filePath = path.resolve("public" + pathName); console.log(filePath); //獲取對應文件的文檔類型 //我們通過path.extname來獲取文件的後綴名。由於extname返回值包含”.”,所以通過slice方法來剔除掉”.”, //對於沒有後綴名的文件,我們一律認為是unknown。 var ext = path.extname(pathName); ext = ext ? ext.slice(1) : ‘unknown‘; //未知的類型一律用"text/plain"類型 var contentType = mime[ext] || "text/plain"; fs.stat(filePath, (err, stats) => { if (err) { response.writeHead(404, { "content-type": "text/html" }); response.end("<h1>404 Not Found</h1>"); } //沒出錯 並且文件存在 if (!err && stats.isFile()) { readFile(filePath, contentType); } //如果路徑是目錄 if (!err && stats.isDirectory()) { var html = "<head><meta charset = ‘utf-8‘/></head><body><ul>"; //讀取該路徑下文件 fs.readdir(filePath, (err, files) => { if (err) { console.log("讀取路徑失敗!"); } else { //做成一個鏈接表,方便用戶訪問 var flag = false; for (var file of files) { //如果在目錄下找到index.html,直接讀取這個文件 if (file === "index.html") { readFile(filePath + (filePath[filePath.length-1]==‘/‘ ? ‘‘ : ‘/‘) + ‘index.html‘, "text/html"); flag = true; break; }; html += `<li><a href=‘${file}‘>${file}</a></li>`; } if(!flag) { html += ‘</ul></body>‘; response.writeHead(200, { "content-type": "text/html" }); response.end(html); } } }); } //讀取文件的函數 function readFile(filePath, contentType){ response.writeHead(200, { "content-type": contentType }); //建立流對象,讀文件 var stream = fs.createReadStream(filePath); //錯誤處理 stream.on(‘error‘, function() { response.writeHead(500, { "content-type": contentType }); response.end("<h1>500 Server Error</h1>"); }); //讀取文件 stream.pipe(response); } }); }

這個配置可以對文件的類型,路徑進行解析。應為我的項目路徑是

技術分享圖片

所以我這個js配置這個寫的是public大家可根據自己項目路徑來配置

   //__dirname是訪問項目靜態資源的路徑 我的項目靜態文件都在public下所以我寫public可根據自己項目路徑來配置
  var filePath = path.resolve("public" + pathName);

然後直接啟動 node node.js項目就跑起來了,靜態文件全部正確加載了,跳轉鏈接也可以用.

用node.js搭建一個靜態資源站 html,js,css正確加載 跳轉也完美實現!