background

In NodeJS Web service, we sometimes need to put some static files into a folder, allowing arbitrary access, such as CSS, JS, HTML files, or files that users can download. We implement it using koa-static-server.

Why koA-static-Server

Koa-static-server can easily specify rootDir as the new directory of the local physical folder. You can specify rootPath to specify the base path of the URL. For example, a URL starting with /public corresponds to a local./public folder.

rootDir {string} directory that is to be served

rootPath {string} optional rewrite path, defaults to “/”

The installation

$ npm install koa-static-server
Copy the code

use

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'}))
Copy the code

reference

www.npmjs.com/package/koa…