koa 练习

const koa = require('koa')
const path = require('path')
const fs = require('fs')
const mimes = require('./util/mimes.js')

var app = new koa()
app.use(async ctx => {
    let fullStaticPath = path.join(__dirname, './static')

    let _content = await content(ctx, fullStaticPath)

    let _mime = praseMime(ctx.url)

    if (_mime) {
        ctx.type = _mime
    }

    ctx.body = _content
})

app.listen(3000)

console.log('[demo] static-server is starting at port 3000')

/**
 * 获取静态资源内容
 *
 * @param {object} ctx koa上下文
 * @param {string} fullStaticPath 静态资源目录在本地的绝对路径
 * @return  {string} 请求获取到的本地内容
 */
async function content(ctx, fullStaticPath) {
    let reqPath = path.join(fullStaticPath, ctx.url)
    console.log('reqPath:', reqPath)

    let exist = fs.existsSync(reqPath)
    console.log('exist:', exist)
    let content = ''

    if (!exist) {
        content = '404 Not Found'
    } else {
        let stat = fs.statSync(reqPath)
        console.log('stat:', stat)

        if (stat.isDirectory()) {
            let contentList = fs.readdirSync(reqPath)
            console.log('contentList:', contentList)
            let html = `<ul>`

            for (let [index, item] of contentList.entries()) {
                html = `${html}<li><a href="${ctx.url === '/' ? '' : ctx.url}/${item}">${item}</a>`
            }

            content = `${html}</ul>`
        } else {
            content = await fs.readFileSync(reqPath, 'binary')
        }
    }

    console.log('content:', content)
    return content
}

/**
 * 解析资源类型
 *
 * @param {string} url ctx.url
 */
function praseMime(url) {
    let extName = path.extname(url)
    console.log('extName:', extName)
    extName = extName ? extName.slice(1) : 'unknown'

    return mimes[extName]
}
let mimes = {
    'css': 'text/css',
    'less': 'text/css',
    'gif': 'image/gif',
    'html': 'text/html',
    'ico': 'image/x-icon',
    'jpeg': 'image/jpeg',
    'jpg': 'image/jpeg',
    'js': 'text/javascript',
    'json': 'application/json',
    'pdf': 'application/pdf',
    'png': 'image/png',
    'svg': 'image/svg+xml',
    'swf': 'application/x-shockwave-flash',
    'tiff': 'image/tiff',
    'txt': 'text/plain',
    'wav': 'audio/x-wav',
    'wma': 'audio/x-ms-wma',
    'wmv': 'video/x-ms-wmv',
    'xml': 'text/xml'
  }
 
  module.exports = mimes

实现静态资源服务器,熟悉nodejs文件及目录的读写以及koa基础

猜你喜欢

转载自www.cnblogs.com/fengyouqi/p/10953973.html
koa