• NodeJS4-3静态资源服务器实战_优化成近似同步写法


    实例3 上面有点回调,优化成近似同步的写法

    route.js

    const fs =require('fs')
    const promisify = require('util').promisify;
    const stat = promisify(fs.stat)
    const readdir = promisify(fs.readdir);
    module.exports=async function(req,res,filePath){
        
        try{
            const stats =await stat(filePath)
            if(stats.isFile()){
                res.statusCode = 200
                res.setHeader('content-Type','text/plain')
                fs.createReadStream(filePath).pipe(res);
                // fs.readFile(filePath,(err,data)=>{
                //     res.end(data)
                // });
            }else if(stats.isDirectory()){
                //所有异步调用必须用await
                const files =await readdir(filePath);
                res.statusCode = 200
                res.setHeader('content-Type','text/plain')
                res.end(files.join(','));
            }
        }catch(ex){
            console.error(ex);
            res.statusCode = 404
            res.setHeader('content-Type','text/plain')
            res.end(`${filePath} is not a directory or file
     ${ex.error}`)
        }
    }

    app.js

    const http = require('http');
    const chalk = require('chalk')
    const  path = require('path')
    const conf = require('./config/defaultConfig.js');
    const route = require('./config/helper/route')
    const server = http.createServer((req,res)=>{
        const url = req.url;
        //拿到文件路径
        const filePath = path.join(conf.root,req.url)
        route(req,res,filePath)
    });
    
    server.listen(conf.port,conf.hostname,()=>{
        const addr = `http://${conf.hostname}:${conf.port}`;
        console.log(`Server started at ${chalk.green(addr)}`);  
    })
  • 相关阅读:
    程序猿小白博客报道
    UML
    mysql隔离级别相关
    mac使用相关笔记
    git相关
    maven相关
    springboot相关
    guava
    IDEA高效运用技巧
    spring事务相关
  • 原文地址:https://www.cnblogs.com/chorkiu/p/11429477.html
Copyright © 2020-2023  润新知