美文网首页
Node搭建静态资源服务器

Node搭建静态资源服务器

作者: visitor009 | 来源:发表于2020-05-19 21:18 被阅读0次

    起步

    mime 获取文件类型

    npm init -y
    npm i mime koa
    

    app.js

    /* 
    1. 获取请求资源路径
    2. 判断是否存在
    3. 获取请求资源类型,设置http 响应头
    4. 在http响应头 body 中返回 */
    const Koa = require('koa');
    const app = new Koa();
    const path = require('path');
    const fs = require('fs');
    const mime = require('mime');
    const root = path.resolve('.');
    
    app.use(async (ctx, next) => {
        if (ctx.path.startsWith('/static/')) {
            let requestPath = ctx.path;
            let filePath = path.join(root,requestPath);
            if (fs.existsSync(filePath)) {
                ctx.response.status == 200
                ctx.response.set('Content-Type',mime.getType(requestPath)) // 设置正确的文件类型,否则返回的文件后缀有问题
                // 文件需要下载时启用此字段
                // ctx.response.set('Content-Disposition','attachment') 
                ctx.response.body = fs.createReadStream(filePath)
            } else {
                ctx.response.status == 404
            }
        }
    });
    
    app.listen(3000);
    console.log('app started at port 3000...');
    

    http 文档
    Node 教程

    相关文章

      网友评论

          本文标题:Node搭建静态资源服务器

          本文链接:https://www.haomeiwen.com/subject/nfpbohtx.html