首頁  >  文章  >  web前端  >  node靜態檔案伺服器實例詳解

node靜態檔案伺服器實例詳解

小云云
小云云原創
2018-03-12 09:35:001267瀏覽

本文主要和大家介紹了實戰node靜態檔案伺服器的範例,本文首先會列出它的功能然後再以程式碼的形式分享給大家,希望能幫助到大家。

支援功能:

  1. 讀取靜態檔案

  2. #存取目錄可以自動尋找下面的index.html檔案, 如果沒有index.html則列出檔案清單

  3. MIME類型支援

  4. 快取支援/控制

  5. 支援gzip壓縮

  6. Range支持,斷點續傳

  7. 全域指令執行

  8. 子程序運行

1. 建立服務讀取靜態檔案

首先引入http模組,建立一個伺服器,並監聽設定埠:

 const http = require('http');
 
 const server = http.createServer();
 
 // 监听请求
 server.on('request', request.bind(this));
 
 server.listen(config.port, () => {
  console.log(`静态文件服务启动成功, 访问localhost:${config.port}`);
 });

寫一個fn專門處理請求, 返回靜態檔案, url模組取得路徑:

 const url = require('url');
 const fs = require('fs');
 function request(req, res) {
 const { pathname } = url.parse(req.url); // 访问路径
 
 const filepath = path.join(config.root, pathname); // 文件路径
 
 fs.createReadStream(filepath).pipe(res); // 读取文件,并响应
 }

支援尋找index.html:

 if (pathname === '/') {
  const rootPath = path.join(config.root, 'index.html');
  try{
   const indexStat = fs.statSync(rootPath);
   if (indexStat) {
    filepath = rootPath;
   }
  } catch(e) {
   
  }
 }

存取目錄時,列出檔案目錄:

 fs.stat(filepath, (err, stats) => {
 if (err) {
  res.end('not found');
  return;
 }
 if (stats.isDirectory()) {
  let files = fs.readdirSync(filepath);
  files = files.map(file => ({
   name: file,
   url: path.join(pathname, file)
  }));
  let html = this.list()({
   title: pathname,
   files
  });
  res.setHeader('Content-Type', 'text/html');
  res.end(html);
 }
 }

html模板:

 function list() {
  let tmpl = fs.readFileSync(path.resolve(__dirname, 'template', 'list.html'), 'utf8');
  return handlebars.compile(tmpl);
 }
 76c82f278ac045591c9159d381de2c57
 9fd01892b579bba0c343404bcccd70fb
 93f0f5c25f18dab9d176bd4f6de5d30e
 a80eb7cbb6fff8b0ff70bae37074b813
 8f6d5a544bbc0d98e0f297ef053f784d
 ef0e6bda9678de73355aeb4407692a87
 b2386ffb911b14667cb8f0f91ea547a7{{title}}6e916e0f7d1e588d4f442bf645aedb2f
 9c3bca370b5104690d9ef395f2c5f8d1
 6c04bd5ca3fcae76e30b72ad730ca86d
 4a249f0d628e2318394fd9b75b4636b1hope-server静态文件服务器473f0a7621bec819994bb5020d29372a
 ff6d136ddc5fdfeffaf53ff6ee95f185
  {{#each files}}
  25edfb22a4f469ecb59f1190150159c6
   0e8c1c10a7257f38575c59bd16d77a1a{{name}}5db79b134e9f6b82c0b36e0489ee08ed
  bed06894275b65c1ab86501b08a632eb
  {{/each}}
 929d1f5ca49e04fdcb27f9465b944689
 36cc49f0c466276486e50c850b7e4956
 73a6ac4ed44ffec12cee46588e518a5e

2.MIME類型支援

利用mime模組得到檔案類型,並設定編碼:

res.setHeader('Content-Type', mime.getType(filepath) + ';charset=utf-8');

3.快取支援

#http協定快取:

Cache-Control: http1.1內容,告訴客戶端如何快取數據,以及規則

  1. private 用戶端可以快取

  2. public 用戶端和代理伺服器都可以快取

  3. #max-age=60 快取內容會在60秒後失效

  4. no-cache 需要使用對比緩存驗證資料,強制向來源伺服器再次驗證

  5. no-store 所有內容都不會緩存,強制快取和對比快取都不會觸發

Expires: http1.0內容,cache-control會覆蓋,告訴客戶端快取何時過期

ETag: 內容的hash值下次客戶端請求在請求頭裡添加if-none-match: etag值

Last-Modified: 最後的修改時間下一次客戶端請求在請求頭裡添加if-modified-since: Last-Modified值

 handleCache(req, res, stats, hash) {
 // 当资源过期时, 客户端发现上一次请求资源,服务器有发送Last-Modified, 则再次请求时带上if-modified-since
 const ifModifiedSince = req.headers['if-modified-since'];
 // 服务器发送了etag,客户端再次请求时用If-None-Match字段来询问是否过期
 const ifNoneMatch = req.headers['if-none-match'];
 // http1.1内容 max-age=30 为强行缓存30秒 30秒内再次请求则用缓存 private 仅客户端缓存,代理服务器不可缓存
 res.setHeader('Cache-Control', 'private,max-age=30');
 // http1.0内容 作用与Cache-Control一致 告诉客户端什么时间,资源过期 优先级低于Cache-Control
 res.setHeader('Expires', new Date(Date.now() + 30 * 1000).toGMTString());
 // 设置ETag 根据内容生成的hash
 res.setHeader('ETag', hash);
 // 设置Last-Modified 文件最后修改时间
 const lastModified = stats.ctime.toGMTString();
 res.setHeader('Last-Modified', lastModified);
 
 // 判断ETag是否过期
 if (ifNoneMatch && ifNoneMatch != hash) {
  return false;
 }
 // 判断文件最后修改时间
 if (ifModifiedSince && ifModifiedSince != lastModified) {
  return false;
 }
 // 如果存在且相等,走缓存304
 if (ifNoneMatch || ifModifiedSince) {
  res.writeHead(304);
  res.end();
  return true;
 } else {
  return false;
 }
 }

4.壓縮

客戶端發送內容,透過請求頭裡Accept-Encoding: gzip, deflate告訴伺服器支援哪些壓縮格式,伺服器根據支援的壓縮格式,壓縮內容。如伺服器不支持,則不壓縮。

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

5.斷點續傳

伺服器透過請求頭中的Range: bytes=0-xxx來判斷是否是做Range請求,如果這個值存在而且有效,則只發回請求的那部分文件內容,回應的狀態碼變成206,表示Partial Content,並設定Content-Range。如果無效,則傳回416狀態碼,表示Request Range Not Satisfiable。如果不包含Range的請求頭,則繼續以常規的方式回應。

 getStream(req, res, filepath, statObj) {
  let start = 0;
  let end = statObj.size - 1;
  const 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
  });
 }

6.全域指令執行

透過npm link實作

  1. #為npm包目錄建立軟鏈接,將其鍊到{prefix}/ lib/node_modules/

  2. 為可執行檔(bin)建立軟鏈接,將其鏈到{prefix}/bin/{name}

npm link指令透過連結目錄和可執行文件,實作npm包指令的全域可執行。

package.json裡面配置

 {
 bin: {
 "hope-server": "bin/hope"
 }
 }

在專案下面建立bin目錄hope檔案, 利用yargs設定命令列傳參數

 // 告诉电脑用node运行我的文件
 #! /usr/bin/env node
 
 const yargs = require('yargs');
 const init = require('../src/index.js');
 const 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: 8080,
 description: '配置端口号'
 }).option('c', {
 alias: 'child',
 demand: 'false',
 type: 'boolean',
 default: false,
 description: '是否子进程运行'
 })
 .usage('hope-server [options]')
 .example(
 'hope-server -d / -p 9090 -o localhost', '在本机的9090端口上监听客户端的请求'
 ).help('h').argv;
 
 // 启动服务
 init(argv);

7.子進程運行

透過spawn實作

index.js

 const { spawn } = require('child_process');
 const Server = require('./hope');
 function init(argv) {
  // 如果配置为子进程开启服务
  if (argv.child) {
   //子进程启动服务
   const child = spawn('node', ['hope.js', JSON.stringify(argv)], {
    cwd: __dirname,
    detached: true,
    stdio: 'inherit'
   });
 
   //后台运行
   child.unref();
   //退出主线程,让子线程单独运行
   process.exit(0);
  } else {
   const server = new Server(argv);
   server.start();
  }
 }
 
 module.exports = init;
hope.js
 if (process.argv[2] && process.argv[2].startsWith('{')) {
 const argv = JSON.parse(process.argv[2]);
 const server = new Hope(argv);
 server.start();
 }

8.原始碼及測試

原始碼位址: hope-server

npm install hope-server -g

進入任意目錄

hope-server

相關推薦:

node靜態檔案伺服器詳解

使用nodejs、Python寫的一個簡易HTTP靜態檔案伺服器

Node.js靜態檔案伺服器改進版_node.js

#

以上是node靜態檔案伺服器實例詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn