const Koa = require('koa');
const app = new Koa();
app.use(staticServer('./static'))
app.use(staticServer('./static/img'))
const server = app.listen(8899, (res) => {
console.log('服务已启动...')
})
console.log(server.address().port)
const send = require('koa-send')
const server = (root, opts = {}) => {
opts.root = resolve(root)
return async function serve(ctx, next) {
await next()
if (ctx.method !== 'HEAD' && ctx.method !== 'GET') return
if (ctx.body != null || ctx.status !== 404) return
try {
await send(ctx, ctx.path, opts)
} catch(error) {
}
}
}
module.export = server
const fs = require('fs');
const fsPromise = fs.promises;
const { stat, access } = fsPromise;
const { resolve, normalize, basename, extname, parse, sep, format } = require('path')
function decode(path) {
try {
return decodeURIComponent(path)
} catch (err) {
return -1
}
}
const send = async(ctx, path, opts = {}) => {
const root = opts.root ? normalize(resolve(opts.root)) : '';
path = decode(path)
if (path === -1) return ctx.throw(400, 'failed to decode');
path = resolve(root, path)
let stats
try {
stats = await stat(path)
} catch (err) {
err.status = 500
throw err
}
ctx.set('Content-Length', stats.size)
if (!ctx.type) ctx.type = extname(path)
ctx.body = fs.createReadStream(path)
return path
}
module.export = send