最近用node搞了一個靜態服務器,也就是跑一條server,用于提供靜態資源訪問的功能,如圖片、CSS、JS等,
支持對CSS、JS、html、png等資源訪問
廢話少說,怎么實作呢?
少俠別急,我們需要一個MIME支持,已經有熱心人士整理好了:點擊前往下載
將內容復制到一個mime.json檔案里,就可以進行下面的操作了,
目錄結構如下:

新建一個staticServer.js檔案:
const fs = require('fs');
const path = require('path');
let mime = require('./public/mime.json')
module.exports = (req, res, rootPath) => {
fs.readFile(path.join(rootPath, req.url), (err, data) => {
if(err){
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
res.end("500 服務器開小差了!!程式猿小哥正在修復中...");
}else{
let ext = path.extname(req.url);
let mimeType = mime[ext];
res.writeHead(200, { 'Content-Type': `${mimeType}; charset=utf-8` });
res.write(data);
res.end();
}
})
}
這里匯出的函式有三個引數,分別是request,response和拼接路徑用的rootPath,指的是靜態服務器的存放根目錄,通過path模塊拼接rootPath和請求的url,如果請求正確則獲取路徑的擴展名,以擴展名為鍵獲取mime的值,這里的mime就是從mime.json匯入進來的,再動態生成Content-Type,最后通過response的write方法將檔案內容展示到網頁,
在程式入口index.js中:
const http = require('http');
const path = require('path');
let staticServer = require('./staticServer');
let root = path.join(__dirname, 'www');
http.createServer( (req, res) => {
staticServer(req, res, path.join(root));
}).listen(8081, ()=>{
console.log('Express started on http://localhost:' +8080)
})
我們只需要匯入staticServer的模塊,再傳入靜態檔案根目錄呼叫即可,
在這里靜態服務器已經完成了!如果你不想看效果,可不用繼續往下看噢,
我們在上面定義的根目錄__dirname+“www”,新建三個檔案,分別為index.html、index.css、index.js,
<!--index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./index.css">
<title>Document</title>
</head>
<body>
<h1>hello nodejs</h1>
<script src="./index.js"></script>
</body>
</html>
<!--index.js-->
console.log("666")
<!--index.css-->
:root{
--bgcolor: #000;
--color: yellowgreen
}
body {
background-color: var(--bgcolor)
}
html {
color: var(--color)
}
我們通過node index啟動服務器,訪問本地服務器下的index.html,效果如下:


可以看到,我們靜態資源已經請求到了!
可請求的資源型別都包含在mime.json里面,基本上都包含了,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/233563.html
標籤:其他
上一篇:7-21 逆序數 (10分)
