Node之手寫靜態資源服務器

背景

學習服務端知識,入門就是要把文件掛載到服務器上,咱們才能去訪問相應的文件。本地開發的時候,咱們也會常常把文件放在服務器上去訪問,以便達到在同一個局域網內,經過同一個服務器地址訪問相同的文件,好比咱們會用xampp,會用sulime的插件sublime-server等等。本篇文章就經過node,手寫一個靜態資源服務器,以達到你能夠隨意定義任何一個文件夾爲根目錄,去訪問相應的文件,達到anywhere is your static-server。html

主要實現功能

  1. 讀取靜態文件
  2. 靜態資源緩存
  3. 資源壓縮
  4. MIME類型支持
  5. 斷點續傳
  6. 發佈爲可執行命令並能夠後臺運行,能夠經過npm install -g安裝

Useage

//install
$ npm i st-server -g
//forhelp
$ st-server -h
//start
$ st-server
// or with port
$ st-server -p 8800
// or with hostname
$ st-server -o localhost -p 8888
// or with folder
$ st-server -d / 
// full parameters
$ st-server -d / -p 9900 -o localhost
複製代碼

其中能夠配置三個參數,-d表明你要訪問的根目錄,-p表明端口號(目前暫不支持屢次開啓用同一個端口號,須要手動殺死以前的進程),-o表明hostname。 全部源代碼已經上傳至githubnode

源碼分析

  • 所有代碼基於一個StaticServer類進行實現,在構造函數中首先引入全部的配置,argv是經過命令行敲入傳進來的參數,而後在獲取須要編譯的模板,該模板是簡單的顯示一個文件夾下全部文件的列表。基於handlebars實現。而後開啓服務,監聽請求,由this.request()處理
class StaticServer{
    constructor(argv){
        this.config = Object.assign({},config,argv);
        this.compileTpl = compileTpl();
    }
    startServer(){
        let server = http.createServer();
        server.on('request',this.request.bind(this));
        server.listen(this.config.port,()=>{
            let serverUrl = `http://${this.config.host}:${this.config.port}`;
            debug(`服務已開啓,地址爲${chalk.green(serverUrl)}`);
        })
    }
}
複製代碼
  • 主線就是讀取想要搭建靜態服務的地址,若是是文件夾,則查找該文件夾下是否有index.html文件,有則顯示,沒有則列出全部的文件;若是是文件的話,則直接顯示該文件內容。大前提在顯示具體的文件以前,要判斷有沒有緩存,有直接獲取緩存,沒有的話再請求服務器。
async request(req,res){
        let {pathname} = url.parse(req.url);
        if(pathname == '/favicon.ico'){
            return this.sendError('NOT FOUND',req,res);
        }
        //獲取須要讀的文件目錄
        let filePath = path.join(this.config.root,pathname);
        let statObj = await fsStat(filePath);
        if(statObj.isDirectory()){//若是是一個目錄的話 列出目錄下面的內容
            let files = await readDir(filePath);
            let isHasIndexHtml = false;
            files = files.map(file=>{
                if(file.indexOf('index.html')>-1){
                    isHasIndexHtml = true;
                }
                return {
                    name:file,
                    url:path.join(pathname,file)
                }
            })
            if(isHasIndexHtml){
                let statObjN = await fsStat(filePath+'/index.html');
                return this.sendFile(req,res,filePath+'/index.html',statObjN);
            }
            let resHtml = this.compileTpl({
                title:filePath,
                files
            })
            res.setHeader('Content-Type','text/html');
            res.end(resHtml);
        }else{
            this.sendFile(req,res,filePath,statObj);
        }
        
    }
    sendFile(req,res,filePath,statObj){
        //判斷是否走緩存
        if (this.getFileFromCache(req, res, statObj)) return; //若是走緩存,則直接返回
        res.setHeader('Content-Type',mime.getType(filePath)+';charset=utf-8');
        let encoding = this.getEncoding(req,res);
        //常見一個可讀流
        let rs = this.getPartStream(req,res,filePath,statObj);
        if(encoding){
            rs.pipe(encoding).pipe(res);
        }else{
            rs.pipe(res);
        }
    }
複製代碼

sendFile方法就是向瀏覽器輸出內容的方法,主要包括如下幾個重要的點:git

  1. 緩存處理
getFileFromCache(req,res,statObj){
        let ifModifiedSince = req.headers['if-modified-since'];
        let isNoneMatch = req.headers['if-none-match'];
        res.setHeader('Cache-Control','private,max-age=60');
        res.setHeader('Expires',new Date(Date.now() + 60*1000).toUTCString());
        let etag = crypto.createHash('sha1').update(statObj.ctime.toUTCString() + statObj.size).digest('hex');
        let lastModified = statObj.ctime.toGMTString();
        res.setHeader('ETag', etag);
        res.setHeader('Last-Modified', lastModified);
        if (isNoneMatch && isNoneMatch != etag) {
            return false;
        }
        if (ifModifiedSince && ifModifiedSince != lastModified) {
            return false;
        }
        if (isNoneMatch || ifModifiedSince) {
            res.statusCode = 304;
            res.end('');
            return true;
        } else {
            return false;
        }
    }
複製代碼

這裏咱們經過Last-Modified,ETag實現協商緩存,Cache-Control,Expires實現強制緩存,當全部緩存條件成立時纔會生效。Last-Modified原理是經過文件的修改時間,判斷文件是否修改過,ETag經過文件內容的加密判斷是否修改過。Cache-Control,Expire經過時間進行強緩。 2. 對文件進行壓縮,壓縮文件之後能夠減小體積,加快傳輸速度和節約帶寬 ,這裏支持gzip和deflate兩種方式,用node自己的模塊zlib進行處理。github

getEncoding(req,res){
        let acceptEncoding = req.headers['accept-encoding'];
        if(acceptEncoding.match(/\bgzip\b/)){
            res.setHeader('Content-Encoding','gzip');
            return zlib.createGzip();
        }else if(acceptEncoding.match(/\bdeflate\b/)){
            res.setHeader('Conetnt-Encoding','deflate');
            return zlib.createDeflate();
        }else{
            return null;
        }
    }
複製代碼
  1. 經過range,進行斷點續傳的處理
getPartStream(req,res,filePath,statObj){
        let start = 0;
        let end = statObj.size -1;
        let range = req.headers['range'];
        if(range){
            res.setHeader('Accept-Range','bytes');
            res.statusCode = 206;
            let result = range.match(/bytes=(\d*)-(\d*)/);
            if(result){
                start = isNaN(result[1]) ? start : parseInt(result[1]);
                end = isNaN(result[2]) ? end : parseInt(result[2]) - 1;
            }
        }
        return fs.createReadStream(filePath,{
            start,end
        })
    }
複製代碼
  1. 生成命令行工具,用npm安裝yargs包進行操做,並在package.json中添加 "bin": { "st-Server": "bin/www" },指向須要執行命令的文件,而後在www中配置對應的命令,而且開啓子進程進行主代碼的操做,爲了解決你開啓命令後,命令行一直處於卡頓的狀態。開啓子進程也是node原生模塊child_process支持的。
#! /usr/bin/env node

let yargs = require('yargs');
let argv = yargs.option('d', {
    alias: 'root',
    demand: 'false',
    type: 'string',
    default: process.cwd(),
    description: '靜態文件根目錄'
}).option('o', {
    alias: 'host',
    demand: 'false',
    default: 'localhost',
    type: 'string',
    description: '請配置監聽的主機'
}).option('p', {
    alias: 'port',
    demand: 'false',
    type: 'number',
    default: 8800,
    description: '請配置端口號'
})
    .usage('st-server [options]')
    .example(
    'st-server -d / -p 9900 -o localhost', '在本機的9900端口上監聽客戶端的請求'
    ).help('h').argv;

let path = require('path');
let {
 spawn
} = require('child_process');

let p1 = spawn('node', ['www.js', JSON.stringify(argv)], {
 cwd: __dirname
});
p1.unref();
process.exit(0);
複製代碼

參考

anywherenpm

相關文章
相關標籤/搜索