極簡 Node.js 入門 – 5.3 靜態資源伺服器

極簡 Node.js 入門系列教程://www.yuque.com/sunluyong/node

本文更佳閱讀體驗://www.yuque.com/sunluyong/node/static-server

創建 HTTP 伺服器實現了一個最簡單的靜態資源伺服器,可以對程式碼進行寫改造,增加文件夾預覽功能,暴露出一些配置,變成一個可訂製的靜態資源伺服器模組

模組化

可訂製的靜態資源伺服器理想的使用方式應該是這樣的

const StaticServer = require('YOUR_STATIC_SERVER_FILE_PATH');

const staticServer = new StaticServer({
	port: 9527,
  root: '/public',
});

staticServer.start();

staticServer.close();

這樣的使用方式就要求程式碼實現模組化,Node.js 實現一個模組非常簡單

const http = require('http');
const fs = require('fs');
const path = require('path');
const mime = require('mime-types');

const defaultConf = require('./config');

class StaticServer {
  constructor(options = {}) {
    this.config = Object.assign(defaultConf, options);
  }

  start() {
    const { port, root } = this.config;

    this.server = http.createServer((req, res) => {
      const { url, method } = req;

      if (method !== 'GET') {
        res.writeHead(404, {
          'content-type': 'text/html',
        });
        res.end('請使用 GET 方法訪問文件!');
        return false;
      }

      const filePath = path.join(root, url);
      fs.access(filePath, fs.constants.R_OK, err => {
        if (err) {
          res.writeHead(404, {
            'content-type': 'text/html',
          });
          res.end('文件不存在!');

        } else {
          res.writeHead(200, {
            'content-type': mime.contentType(path.extname(url)),
          });
          fs.createReadStream(filePath).pipe(res);
        }
      });
    }).listen(port, () => {
      console.log(`Static server started at port ${port}`);
    });
  }

  stop() {
    this.server.close(() => {
      console.log(`Static server closed.`);
    });
  }
}

module.exports = StaticServer;

完整程式碼://github.com/Samaritan89/static-server/tree/v1
執行 npm run test 可以測試
image.png
image.png

支援文件夾預覽

當訪問的路徑是文件夾的時候程式會報錯

Error: EISDIR: illegal operation on a directory, read
Emitted 'error' event on ReadStream instance at:
    at internal/fs/streams.js:217:14
    at FSReqCallback.wrapper [as oncomplete] (fs.js:524:5) {
  errno: -21,
  code: 'EISDIR',
  syscall: 'read'
}

因為 fs.createReadStream 嘗試讀取文件夾,需要兼容下訪問路徑是文件夾的時候,返回一個目錄頁,也就是在 fs.access 之後判斷文件類型

fs.access(filePath, fs.constants.R_OK, err => {
  if (err) {
    res.writeHead(404, {
      'content-type': 'text/html',
    });
    res.end('文件不存在!');

  } else {
    const stats = fs.statSync(filePath);
    const list = [];
    if (stats.isDirectory()) {
      // 如果是文件夾則遍歷文件夾,生成改文件夾內的文件樹
      // 遍歷文件內容,生成 html

    } else {
      res.writeHead(200, {
        'content-type': mime.contentType(path.extname(url)),
      });
      fs.createReadStream(filePath).pipe(res);
    }
  }
});

遍歷生成 html 部分需要用到 文件夾操作 章節介紹的知識,為了方便生成 HTML,demo 使用了 Handlebar 模板引擎,主要邏輯

if (stats.isDirectory()) {
  // 如果是文件夾則遍歷文件夾,生成改文件夾內的文件樹
  const dir = fs.opendirSync(filePath);
  let dirent = dir.readSync();
  while (dirent) {
    list.push({
      name: dirent.name,
      path: path.join(url, dirent.name),
      type: dirent.isDirectory() ? 'folder' : 'file',
    });
    dirent = dir.readSync();
  }
  dir.close();

  res.writeHead(200, {
    'content-type': 'text/html',
  });

  // 對文件順序重排,文件夾在文件前面,相同類型按字母排序,不區分大小寫
  list.sort((x, y) => {
    if (x.type > y.type) {
      // 'folder' > 'file', 返回 -1,folder 在 file 之前
      return -1;
    } else if (x.type == y.type) {
      return compare(x.name.toLowerCase(), y.name.toLowerCase());
    } else {
      return 1;
    }
  });

  // 使用 handlebars 模板引擎,生成目錄頁面 html
  const html = template({ list });
  res.end(html);
}

通過 git 程式碼修改記錄可以清晰看到本次的變更://github.com/Samaritan89/static-server/commit/5565788dc317f29372f6e67e6fd55ec92323d0ea

同樣在項目根目錄執行 npm run test ,使用瀏覽器訪問 127.0.0.1:9527 可以看到目錄文件的展示
image.png
完整程式碼://github.com/Samaritan89/static-server/tree/v2

Tags: