NodeJS 使用 koa-static-server 实现静态文件服务

591 阅读1分钟

背景

在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'}))

参考

www.npmjs.com/package/koa…