zoukankan      html  css  js  c++  java
  • NodeJS4-2静态资源服务器实战_实现获取文件路径

    实例2 : 实现获取文件路径,判断是文件还是文件夹,如果是文件夹就显示里面的列表文件,如果是文件就显示里面的内容

    defaultConfig.js

    module.exports={
        root:process.cwd(),
        hostname:'127.0.0.1',
        port:9527
    }

    app.js

    const http = require('http');
    const chalk = require('chalk')
    const  path = require('path')
    const fs =require('fs')
    const conf = require('./config/defaultConfig.js');
    const server = http.createServer((req,res)=>{
        const url = req.url;
        //拿到文件路径
        const filePath = path.join(conf.root,req.url)
        // 判断是一个文件夹还是一个文件
        fs.stat(filePath,(err,stats)=>{
            if(err){
                res.statusCode = 404
                res.setHeader('content-Type','text/plain')
                res.end(`${filePath} is not a directory or file`)
                return 
            }
    
            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()){
                fs.readdir(filePath,(err,files)=>{
                    res.statusCode = 200
                    res.setHeader('content-Type','text/plain')
                    res.end(files.join(','));
                })
            }
        })
    });
    
    server.listen(conf.port,conf.hostname,()=>{
        const addr = `http://${conf.hostname}:${conf.port}`;
        console.log(`Server started at ${chalk.green(addr)}`);  
    })
  • 相关阅读:
    路由的配置,侧边栏类名与url的结合运用
    bootstrap面包屑在ie8下显示重叠,鼠标点击显示效果正常
    JS代码判断IE6,IE7,IE8,IE9!
    wampserver配置服务
    HTML5 20180918----20180921
    HTML5 20180921
    HTML5 20180920
    HTML5 20180919
    HTML5 20180918
    HTTP协议
  • 原文地址:https://www.cnblogs.com/chorkiu/p/11429472.html
Copyright © 2011-2022 走看看