UNPKG

1.03 kBJavaScriptView Raw
1/**
2 * Created by liuzhengdong on 2018/4/10.
3 * file中间件 开发模式用,方便 ajax读取.json .text文件
4 * @param {ctx} ctx koa ctx
5 */
6const fs = require('fs')
7const path = require('path')
8const logger = require('./../logger/koa-logger')('fileMiddle')
9module.exports = async function(ctx, next) {
10 const proxy = Object.keys(require(path.join(process.cwd(), 'app.config')).proxy) || []
11 if (proxy.findIndex(val => ctx.url.startsWith(val)) > -1) {
12 await next()
13 } else {
14 const res = ctx.res
15 // res.setHeader('Content-Type', 'application/json; charset=utf-8')
16 let context = 'File does not exist, please insist that the path is correct'
17 try {
18 logger.info('Read File Request Success', `path ----> ${ctx.url}`)
19 context = fs.readFileSync(path.join(process.cwd(), ctx.url), 'utf-8')
20 res.statusCode = 200
21 } catch (err) {
22 logger.info(context, ctx.url)
23 res.statusCode = 404
24 }
25 res.end(context)
26 }
27}