有時候,咱們想讀取一些服務器上的文件,可是又不想寫太複雜的程序,能夠考慮用nodejs,能夠很簡單的寫出一個文件服務器
下面是我寫的一個簡單的文件服務器,能讀取文件夾信息,附帶緩存功能,這是github連接,或者直接複製下面的代碼運行便可,須要安裝mime的依賴javascript
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) => { let reqUrl = decodeURIComponent(req.url); // 中文解碼 const obj = url.parse(reqUrl); // 解析請求的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 if (stats.isDirectory()) { // 讀取文件夾 fs.readdir(realPath, { encoding: 'utf8' }, (err, files) => { res.statusCode = 200; res.setHeader('content-type', 'text/html'); let result = ''; for (let i = 0; i < files.length; i++) { result += `<a href="${req.url}/${files[i]}">${files[i]}</a><br/>`; } let html = ` <!doctype html> <html> <head> <meta charset='utf-8'/> </head> <body> ${result} </body> </html>`; res.end(html); }); } 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後,在規定的時間內仍是會請求服務器,這個還須要再看一下怎麼回事,要是有人瞭解的話能夠告訴我一下,謝謝。html