node部署靜態頁面;node上線靜態頁面

node部署靜態頁面上線

靜態頁面上線能夠採用 nginx, tomcat或者node ,咱們這裏介紹下node部署靜態頁面javascript

這裏採用最簡單的上線方式,咱們就不用node + express + ejs ,直接採用node + htmlcss

1.首先肯定好安裝了 node 若是沒有安裝,請下載 https://nodejs.org/zh-cn/ 建議下載LTS版本html

2.新建一個目錄,好比 test 文件夾,而後在當前文件夾下進入命令行窗口 npm init 初始化npm,此處一路回車,這時會生成 package.json的一個文件java

3.而後咱們須要在 test 的根目錄下建立一個 server.jsnode

  • server.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);
    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);
        }
    });
}

4.這是運行node server.js 便啓動了服務,咱們能夠經過本地 localhost 進行訪問,也可上傳到linux,經過本身域名訪問linux

相關文章
相關標籤/搜索