美文网首页
nodeJS静态服务器

nodeJS静态服务器

作者: ElvisYang1993 | 来源:发表于2018-03-17 01:07 被阅读0次

引入依赖模块

let config = require('./config');
let chalk = require('chalk');//粉笔模块(命令行变色)
let http = require('http');//http模块
let fs = require('fs');//文件模块
let zlib = require('zlib');
let handlebars = require('handlebars');//模板引擎
let url = require('url');//url模块解析请求url
let mime = require('mime');//mime模块通过文件名称/路径拿到内容类型
let path = require('path');
let {promisify,inspect} = require('util');
let stat = promisify(fs.stat);
let readdir = promisify(fs.readdir);
process.env.DEBUG = 'static:*';
let debug = require('debug')('static:app');

编译模板函数

function list() {
    //编译模板,得到渲染方法,传入数据
    let tmpl = fs.readFileSync(path.resolve(__dirname,'src/template','list.html'),'utf8');
    return handlebars.compile(tmpl);//返回一个函数
}

此函数主要用于编译模板,返回一个文件list列表用于返回给客户端。

start方法启动服务

start(){
    //启动服务
    let server = http.createServer();
    server.on('request',this.request.bind(this));
    server.listen(this.config.port,()=>{
        let url = `${this.config.host}:${this.config.port}`;
        debug(`start at ${chalk.green(url)}`);
    })
}

this.config.port可以自己定义端口,debug用于在控制台打印信息。

请求处理方法

async request(req,res){
    //接收请求
    let { pathname } = url.parse(req.url);
    let filepath = path.join(this.config.root,pathname);
    try{
        let statObj = await stat(filepath);
        if(statObj.isDirectory()){//判断是否为目录
            //是目录的话使用handlebars模板引擎渲染目录
            let files = await readdir(filepath);//字符串数组
            files = files.map((file)=>{
                return {
                    name:file,
                    url:path.join(pathname,file)
                }
            });
            let html = this.list({
                title:pathname,
                files:files
            });
            res.setHeader('Content-Type','text/html');
            this.sendFile(req,res,html,statObj,'html');
        }else{
            this.sendFile(req,res,filepath,statObj,'');
        }
    }catch (e){
        debug(inspect(e));
        this.sendError(req,res)
    }
}

这个是主要处理逻辑,首先通过解析客户端的请求url,通过path模块来拿到文件路径,第一个参数是config中配置的静态文件根目录;然后来判断当前请求的是文件还是目录,这里使用一个try catch代码块来捕获异常,如果请求的是个目录的话,遍历这个目录下的所有文件并且将文件名和文件路径传给list编译模板,然后交给发送方法去处理。

发送处理方法

sendFile(req,res,filepath,statObj,type){
    //发送文件
    let expires = new Date(Date.now() + 60 * 1000);
    //缓存设置
    res.setHeader('Expires', expires.toUTCString());
    res.setHeader('Cache-Control', 'max-age=600');
    res.setHeader('Accept-Range', 'bytes');//断点续传
    if(type == 'html'){
        res.end(filepath);
    }else {
        res.setHeader('Content-Type',mime.getType(filepath));
        fs.createReadStream(filepath).pipe(res);
    }
}

发送方法里设置的缓存策略为强制缓存,并且在发送方法里调用zlibFn方法去看客户端请求是否使用压缩,并在最后将内容pipe到res里返回给客户端。

zlib压缩方法

zlibFn(req,res){
    let acceptEncoding = request.headers['accept-encoding'];//压缩
    if (!acceptEncoding) {
        acceptEncoding = '';
    }
    if (acceptEncoding.match(/\bdeflate\b/)) {
        res.setHeader('Content-Encoding','deflate');
        return zlib.createDeflate();
    } else if (acceptEncoding.match(/\bgzip\b/)) {
        res.setHeader('Content-Encoding','gzip');
        return zlib.createGzip();
    } else {
        return null;
    }
}

这里主要是通过请求头中的accept-encoding来判断是否压缩,以何种方式压缩,压缩后返回一个流对象。

初写node静态服务器(简易版)全部代码请见Github

相关文章

  • 2016-08-09学习笔记

    nodejs静态资源服务器 nodejs实例 打开xshell 打开ubuntu 用xshell链接ubuntu...

  • nodejs静态资源服务器

    nodejs静态资源服务器 1、http 是nodejs的服务模块 2、url 是url路由模块 3、fs 是文件...

  • nodejs09-静态服务器+简单ejs+获取form提交的数据

    nodejs 搭建静态web服务器 拆分【07-搭建静态web服务】中http.js 新建model/router...

  • nodeJS静态服务器

    引入依赖模块 编译模板函数 此函数主要用于编译模板,返回一个文件list列表用于返回给客户端。 start方法启动...

  • XDH_LESSON4

    nodeJS 静态服务器简单的服务器 在WM虚拟机ubuntu系统下 创建一个服务器。 const http=re...

  • xdl4

    通过nodejs3个模块写一个静态web服务器 Http File System URL

  • Nodejs实现一个简单的服务器

    之前使用 nodejs 完成了简陋版的静态服务器,了解了服务器的运行机制: 1、创建服务器对象并监听用户请求 2、...

  • nodejs静态资源服务器

    缩写含义 http是nodejs的服务模块 url是url路由模块 fs是文件服务器模块 nodejs服务器的创建...

  • nodejs 静态web服务器

    概述 一般指网站服务器,是指驻留于因特网上某种类型计算机的程序,可以向浏览器等WEB客户端提供文档,也可以放置网站...

  • nodejs搭建静态服务器

    最近想搭建个服务器供局域内的小伙伴使用,以前工作中用过apache和tomcat,可是搭建的过程真的蛮虐的。 后来...

网友评论

      本文标题:nodeJS静态服务器

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