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 ) the console.log ( '[Demo] Starting AT IS static-Server Port 3000' ) / * * * acquiring static resource content * * @param {Object} context CTX KOA * @param {string} fullStaticPath static local resource directory absolute path * @return {string} acquired local content request * / the async function content (CTX, fullStaticPath) { the let reqPath = path.join (fullStaticPath, ctx.url) the console.log ( 'reqPath: ' , reqPath) the let exist = fs.existsSync (reqPath) the console.log ( ' exist: ' , exist) the 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
Achieve a static resource server, familiar nodejs files and directories to read and write as well as the basis of koa