首頁  >  文章  >  web前端  >  Node.js學習之靜態資源伺服器

Node.js學習之靜態資源伺服器

青灯夜游
青灯夜游轉載
2020-12-14 18:20:072764瀏覽

Node.js學習之靜態資源伺服器

相關推薦:《nodejs 教學

#在建立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;

完整程式碼:https://github.com/Samaritan89/ static-server/tree/v1
執行npm run test 可以測試
Node.js學習之靜態資源伺服器
Node.js學習之靜態資源伺服器

##支援資料夾預覽

當存取的路徑是資料夾的時候程式會報錯

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 程式碼修改記錄可以清楚看到本次的變更:https://github.com/Samaritan89/static-server/commit/5565788dc317f29372f6e67e6fd55ec92323d0ea

##npm run test

 ,使用瀏覽器存取127.0.0.1:9527 可以看到目錄檔案的展示##完整程式碼:https://github. com/Samaritan89/static-server/tree/v2
Node.js學習之靜態資源伺服器更多程式相關知識,請造訪:
程式設計教學

! !

以上是Node.js學習之靜態資源伺服器的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:segmentfault.com。如有侵權,請聯絡admin@php.cn刪除