NodeJS 使用 koa-static-server 實現靜態檔案服務
背景
在NodeJS web service 中,有時候我們需要將一些 靜態檔案 放到一個資料夾,允許任意訪問,比如 css,js html 等檔案,或者是允許使用者下載的檔案。我們使用 koa-static-server來實現它。
為什麼選用 koa-static-server
koa-static-server可以方便的指定 rootDir 作為本地物理資料夾的更目錄,可以指定 rootPath 指定url的基礎路徑。比如: /public 開頭的url 對應到本地的 ./public 資料夾內。
rootDir {string} directory that is to be served
rootPath {string} optional rewrite path, defaults to "/"
安裝
$ npm install koa-static-server
使用
var serve = require('koa-static-server') var app = require('koa')() // folder support // GET /web/ // returns /web/index.html // GET /web/file.txt // returns /web/file.txt app.use(serve({rootDir: 'web', rootPath: '/web'}))