node部署靜態頁面上線
靜態頁面上線可以采用 nginx, tomcat或者node ,我們這里介紹下node部署靜態頁面
這里采用最簡單的上線方式,我們就不用node + express + ejs ,直接采用node + html
1.首先確定好安裝了 node 如果沒有安裝,請下載 https://nodejs.org/zh-cn/ 建議下載LTS版本
2.新建一個目錄,比如 test 文件夾,然后在當前文件夾下進入命令行窗口 npm init 初始化npm,此處一路回車,這時會生成 package.json的一個文件
3.然后我們需要在 test 的根目錄下創建一個 server.js
- 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,通過自己域名訪問
