用NodeJS/express-4.0實現的靜態檔案伺服器(serveStatic外掛直接支援HTTP Range請求,因此可用來做mp4流媒體伺服器)
阿新 • • 發佈:2018-12-23
var express = require('express'), serveIndex = require('serve-index'), //只能列表目錄,不能下載檔案? serveStatic = require('serve-static') ; /* $ brew install [email protected] 不使用package.json的依賴安裝方法:以全域性模式(-g)安裝npm依賴,然後npm link命令建立符號連結 $ npm install express -g $ npm link express */ var LOCAL_BIND_PORT = 3000; //express's port var app = express() app.set('x-powered-by', false) app.set('strict routing', true); //路徑/a與/a/是不一樣的(但是/a/*需要單獨指出嗎?) app.set('trust proxy', true); //與Nginx反向代理配合使用? //Trick: app.getOrPost = function(urlPattern, callback){ app.get(urlPattern, callback); app.post(urlPattern, callback); } var REQUEST_GLOBAL_NUM = 1; app.use(function requestNumbering(req, res, next){ var this_request_id = REQUEST_GLOBAL_NUM++; //for dump data file naming; req.request_id = (""+this_request_id).padStart(10, "0") next() }) app.use(function addServerSideIPAddress(req, res, next){//log輸出req.headers,FIXME:怎麼log輸出最終的res.headers? //console.log("["+req.request_id+"] logReqHeaders: req.ip=" + req.ip+" req.socket.localAddress="+req.socket.localAddress); //req.socketLocalIPv4Address = req.socket.localAddress.replace("::ffff:","").replace("::1","127.0.0.1") //dirty hack to fix OS IPv6-first to use IPv4 address only console.log("["+req.request_id+"] req.headers: "+JSON.stringify(req.headers, null, 2)); next(); }) //目錄列表及靜態檔案下載 app.get("/", function(req, res){ res.redirect(302, "/f"); //test direct; }); app.use('/f', serveIndex('/Users/chenzhixiang/', {'icons': true})) //This is Mac OS fs path; var serve = serveStatic('/Users/chenzhixiang/') app.get('/f/*', function(req, res){ req.url = req.url.substring(2); //跳過url中的/f字首,把剩餘的部分對映為相對於/home/chenzx的檔案路徑 console.log("["+req.request_id+"] GET static "+req.url); serve(req, res) }); console.log(`Start static file server at ::${LOCAL_BIND_PORT}, Press ^ + C to exit`) app.listen(LOCAL_BIND_PORT)
serve-index外掛預設生成的列表檢視不是那種詳情列表模式的。