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

node靜態檔案伺服器使用詳解

php中世界最好的语言
php中世界最好的语言原創
2018-03-29 09:18:211446瀏覽

這次帶給大家node靜態檔案伺服器使用詳解,node靜態檔案伺服器使用的注意事項有哪些,下面就是實戰案例,一起來看一下。

本篇文章主要介紹了實戰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);
 }
 <!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 用戶端和代理伺服器都可以快取

  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
相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

use怎麼註冊Vue的全域元件

select的option疊加問題

#

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

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