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


昨天買了一個服務器想着用來測試一些自己的項目,由於是第一次建站,在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</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);
        }
    });
}

 

這個配置可以對文件的類型,路徑進行解析。

因為我的項目靜態資源都在public文件下所以這里就寫成public。大家可根據自己項目路徑來配置

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

這里設置的是端口號,可以根據需要自己來更改

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 () { });//這行代碼作用是項目運行成功后自動打開項目網頁不想要的話可以去掉 });

然后直接啟動 node node.js項目就跑起來了,靜態文件全部正確加載了,跳轉鏈接也可以用。訪問的話直接訪問域名或Ip名就能直接打開項目頁面了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM