首頁  >  文章  >  後端開發  >  node靜態檔案伺服器詳解

node靜態檔案伺服器詳解

小云云
小云云原創
2018-03-09 09:03:541425瀏覽

支援功能:

  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(&#39;Content-Type&#39;, mime.getType(filepath) + &#39;;charset=utf-8&#39;);

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[&#39;if-modified-since&#39;];
 // 服务器发送了etag,客户端再次请求时用If-None-Match字段来询问是否过期
 const ifNoneMatch = req.headers[&#39;if-none-match&#39;];
 // http1.1内容 max-age=30 为强行缓存30秒 30秒内再次请求则用缓存 private 仅客户端缓存,代理服务器不可缓存
 res.setHeader(&#39;Cache-Control&#39;, &#39;private,max-age=30&#39;);
 // http1.0内容 作用与Cache-Control一致 告诉客户端什么时间,资源过期 优先级低于Cache-Control
 res.setHeader(&#39;Expires&#39;, new Date(Date.now() + 30 * 1000).toGMTString());
 // 设置ETag 根据内容生成的hash
 res.setHeader(&#39;ETag&#39;, hash);
 // 设置Last-Modified 文件最后修改时间
 const lastModified = stats.ctime.toGMTString();
 res.setHeader(&#39;Last-Modified&#39;, 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[&#39;accept-encoding&#39;];
  // gzip和deflate压缩
  if (/\bgzip\b/.test(acceptEncoding)) {
   res.setHeader(&#39;Content-Encoding&#39;, &#39;gzip&#39;);
   return zlib.createGzip();
  } else if (/\bdeflate\b/.test(acceptEncoding)) {
   res.setHeader(&#39;Content-Encoding&#39;, &#39;deflate&#39;);
   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[&#39;range&#39;];
  if (range) {
   res.setHeader(&#39;Accept-Range&#39;, &#39;bytes&#39;);
   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(&#39;yargs&#39;);
 const init = require(&#39;../src/index.js&#39;);
 const argv = yargs.option(&#39;d&#39;, {
 alias: &#39;root&#39;,
 demand: &#39;false&#39;,
 type: &#39;string&#39;,
 default: process.cwd(),
 description: &#39;静态文件根目录&#39;
 }).option(&#39;o&#39;, {
 alias: &#39;host&#39;,
 demand: &#39;false&#39;,
 default: &#39;localhost&#39;,
 type: &#39;string&#39;,
 description: &#39;配置监听的主机&#39;
 }).option(&#39;p&#39;, {
 alias: &#39;port&#39;,
 demand: &#39;false&#39;,
 type: &#39;number&#39;,
 default: 8080,
 description: &#39;配置端口号&#39;
 }).option(&#39;c&#39;, {
 alias: &#39;child&#39;,
 demand: &#39;false&#39;,
 type: &#39;boolean&#39;,
 default: false,
 description: &#39;是否子进程运行&#39;
 })
 .usage(&#39;hope-server [options]&#39;)
 .example(
 &#39;hope-server -d / -p 9090 -o localhost&#39;, &#39;在本机的9090端口上监听客户端的请求&#39;
 ).help(&#39;h&#39;).argv;
 
 // 启动服务
 init(argv);

7.子進程運行

#透過spawn實作

##index.js



 const { spawn } = require(&#39;child_process&#39;);
 const Server = require(&#39;./hope&#39;);
 
 function init(argv) {
  // 如果配置为子进程开启服务
  if (argv.child) {
   //子进程启动服务
   const child = spawn(&#39;node&#39;, [&#39;hope.js&#39;, JSON.stringify(argv)], {
    cwd: __dirname,
    detached: true,
    stdio: &#39;inherit&#39;
   });
 
   //后台运行
   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(&#39;{&#39;)) {
 const argv = JSON.parse(process.argv[2]);
 const server = new Hope(argv);
 server.start();
 }

8.原始碼及測試


#原始碼位址: hope-server

##

npm install hope-server -g

進入任意目錄


hope-server

相關推薦:


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

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

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

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

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