簡單的文件服務器
有時候,我們想讀取一些服務器上的文件,但是又不想寫太複雜的程序,可以考慮用nodejs,可以很簡單的寫出一個文件服務器
下面是我寫的一個簡單的文件服務器,附帶緩存功能,這是github鏈接,或者直接複製下面的代碼運行即可,需要安裝mime的依賴
const port = 3004; // 端口號
const http = require('http');
const url = require('url');
const fs = require('fs');
const path = require('path');
const mime = require('mime');
const STATIC_FOLDER = 'public'; // 默認讀取public文件夾下的文件
const IS_OPEN_CACHE = true; // 是否開啓緩存功能
const CACHE_TIME = 10;// 告訴瀏覽器多少時間內可以不用請求服務器,單位:秒
const server = http.createServer((req, res) => {
const obj = url.parse(req.url); // 解析請求的url
let pathname = obj.pathname; // 請求的路徑
if (pathname === '/') {
pathname = './index.html';
}
const realPath = path.join(__dirname, STATIC_FOLDER, pathname); // 獲取物理路徑
// 獲取文件基本信息,包括大小,創建時間修改時間等信息
fs.stat(realPath, (err, stats) => {
let endFilePath = '', contentType = '';
if (err || stats.isDirectory()) {
// 報錯了或者請求的路徑是文件夾,則返回404
res.writeHead(404, 'not found', {
'Content-Type': 'text/plain'
});
res.write(`the request ${pathname} is not found`);
res.end();
} else {
let ext = path.extname(realPath).slice(1); // 獲取文件拓展名
contentType = mime.getType(ext) || 'text/plain';
endFilePath = realPath;
if (!IS_OPEN_CACHE) {
// 未開啓緩存
let raw = fs.createReadStream(endFilePath);
res.writeHead(200, 'ok');
raw.pipe(res);
} else {
// 獲取文件最後修改時間,並把時間轉換成世界時間字符串
let lastModified = stats.mtime.toUTCString();
const ifModifiedSince = 'if-modified-since';
// 告訴瀏覽器在規定的什麼時間內可以不用請求服務器,直接使用瀏覽器緩存,不過貌似沒有生效,需要再學習一下爲什麼
let expires = new Date();
expires.setTime(expires.getTime() + CACHE_TIME * 1000);
res.setHeader("Expires", expires.toUTCString());
res.setHeader('Cache-Control', 'max-age=' + CACHE_TIME);
if (req.headers[ifModifiedSince] && lastModified === req.headers[ifModifiedSince]) {
// 請求頭裏包含請求ifModifiedSince且文件沒有修改,則返回304
res.writeHead(304, 'Not Modified');
res.end();
} else {
// 返回頭Last-Modified爲當前請求文件的最後修改時間
res.setHeader('Last-Modified', lastModified);
// 返回文件
let raw = fs.createReadStream(endFilePath);
res.writeHead(200, 'ok');
raw.pipe(res);
}
}
}
});
});
server.listen(port);
console.log(`server is running at http://localhost:${port}`)
不過目前還有一點問題,服務器緩存返回304,還有修改文件後,再次請求會返回最新文件這個功能目前沒有問題,不過設置的Cache-Control和Expires後,在規定的時間內還是會請求服務器,這個還需要再看一下怎麼回事,要是有人瞭解的話可以告訴我一下,謝謝。