一个简单的Koa框架启动脚本

kevin.Zhu 发布于:2017-5-10 17:08 分类:Nodejs  有 13 人浏览,获得评论 0 条  

//koa框架
const m_koa = require('koa') ;
//静态请求处理中间件
const m_koa_static = require('koa-static') ;
//路由中间件
const m_router = require('koa-router')() ;
//获取请求上传的流
const m_parse = require('co-busboy');
//文件操作
const m_fl = require('fl') ;
//获取流的缓冲区内容
const m_rawbody = require('raw-body') ;
//thunk对象包装器
const thunkify = require('thunkify') ;
//co模块 与thunk对象配合使用
const co = require('co') ;

//koa2.x版本中 router中间件的写法
m_router.get('/up.html', co.wrap(function *(ctx, next)  {
    var my_req = yield m_rawbody(
        ctx.req,
        {
            length: this.length,
            limit: '1mb',
            encoding: this.charset
        }
    ) ;

    //返回http状态码
    //ctx.response.status = 200 ;

    //response的内容
    ctx.body = 'okok' ;
    //console.log(my_req.toString() ) ;
}) ) ;

m_router.post('/post.html', co.wrap(function *(ctx, next)  {
    var my_req = yield m_rawbody(
        ctx.req,
        {
            length: this.length,
            limit: '1mb',
            encoding: this.charset
        }
    ) ;
    ctx.body = 'received post data' ;
    console.log(my_req.toString() ) ;
}) ) ;

//启动服务的初始化函数
function http_start() {
    var app = new m_koa() ;
    var doc_root = __dirname + '/www' ;
    var http_port = 9888 ;
    var server = m_koa_static(doc_root) ;

    //app.use(server) ;
    app.use(server).use(m_router.routes() ).use(m_router.allowedMethods() ) ;

    app.listen(http_port, function () {
        console.log('Server started at port '+ http_port ) ;
    }) ;
}

//启动服务
http_start() ;