node靜態檔案伺服器詳解

來源:互聯網
上載者:User
支援功能:

  1. 讀取靜態檔案

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

  3. MIME類型支援

  4. 緩衝支援/控制

  5. 支援gzip壓縮

  6. Range支援,斷點續傳

  7. 全域命令執行

  8. 子進程運行

本文主要和大家介紹了實戰node靜態檔案伺服器的樣本,希望能協助到大家。

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); }


 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>{{title}}</title> </head> <body> <h1>hope-server靜態檔案伺服器</h1> <ul>  {{#each files}}  <li>   <a href={{url}}>{{name}}</a>  </li>  {{/each}} </ul> </body> </html>

2.MIME類型支援

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


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

3.緩衝支援

http協議緩衝:

Cache-Control: http1.1內容,告訴用戶端如何快取資料,以及規則

  1. private 用戶端可以緩衝

  2. public 用戶端和Proxy 伺服器都可以緩衝

  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 僅用戶端緩衝,Proxy 伺服器不可緩衝 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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.