使用node搭建静态资源服务器(2)

在上一篇使用node搭建静态资源服务器(1)中,我们已经实现了基本的功能,下面继续实现进阶功能。

静态资源的压缩

//compress.js
module.exports = (rs,req,res) => {
   const acceptEncoding = req.headers['accept-encoding'];
   if(!acceptEncoding || !acceptEncoding.match(/\b(gzip|defalte)\b/)) {
       return  rs;
   }else if(acceptEncoding.match(/\bgzip\b/)){
       res.setHeader('Content-Encoding','gzip')
       return rs.pipe(createGzip())
   }else if(acceptEncoding.match(/\defalte\b/)){
       res.setHeader('Content-Encoding','gzip')
       return rs.pipe(creatDeflate())
   }
}

对压缩文件的调用前首先要声明服务器支持对哪些文件类型进行压缩。

//服务器支持的压缩类型,config.js
module.exports = {
    root:process.cwd(),
    hostname:"127.0.0.1",
    port:9876,
    compress:/\.(html|js|css| md|png)/,
        
    }
//对压缩类型进行调用
let rs  =  fs.createReadStream(filePath);
            if(filePath.match(config.compress)){
               rs = compress(rs,req,res)
            }
rs.pipe(res);

对文件类型的判断

我们可以对文件类型进行判断,然后设置对应正确的值,这样可以防止浏览器不能解析引起的乱码等错误。

//mimeType.js
const path = require('path');

const mimeType ={
    'css':'text/css',
    'js':'text/javascript',
    'html':'text/html',
    'json':'application/json',
    'jpeg':'image/jpeg',
    'png':'image/png'

   

}
module.exports = (filePath) => {
  let ext = path.extname(filePath).split('.').pop().toLocaleLowerCase();

  if(!ext) {
      ext = filePath
  }

  return mimeType[ext] || mimeType['html']
}
//对类型判断方法的调用
const contentType = mimeType(filePath);
 res.setHeader('Content-Type', contentType);

自定义端口等

我们在自定义的配置文件里实现了默认的端口,但我们也可以从命令行直接读取配置,这里需要用到node的yargs模块。

//index.js
const yargs = require('yargs');
const Server = require('./app');
const chalk = require('chalk');
const argv = yargs
    .usage('anydoor [options]')
    .option('p',{
        alias:'port',
        describe:'端口号',
        default:9876 
    })
    .option('h',{
        alias:'hostname',
        describe:'host',
        default:'127.0.0.1'
    })
    .option('d',{
        alias:'root',
        describe:'root path',
        default:process.cwd()
    })
    .version()
    .alias('v','version')
    .help()
    .argv;
    

    const server = new Server(argv);
    console.log(chalk.red(argv));
    server.start();

由于要把接收的参数作为配置传递给server,所以我们要对app.js做下修改,让它合并参数,并对外暴露一个server。

const http = require("http");
const chalk = require("chalk");
const path = require('path');
const route = require('./helper/route')
const conf = require('./config/config')

class Server {
    constructor(config) {
        this.config = Object.assign({},conf,config)
    }


    start() {
            const server = http.createServer((req, res) => {
            const filePath = path.join(this.config.root, req.url);
            route(req, res, filePath, this.config);
            
        });

        server.listen(this.config.port, this.config.hostname, () => {
            const addr = `http://${this.config.hostname}:${this.config.port}`;
            console.log(`Server started at ${chalk.green(addr)}`);
        });


    }
}

module.exports = Server;

开发完成我们就可以使用“node src/index.js -p 9999”命令来启动我们的server了,当然你也可以自定义其它信息。

猜你喜欢

转载自www.cnblogs.com/JessicaIsEvolving/p/9463625.html