Node.js学習静的リソースサーバー

青灯夜游
リリース: 2020-12-14 18:20:07
転載
2790 人が閲覧しました

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 の生成を容易にするために、デモでは 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 にアクセスします。ディレクトリ ファイル
Node.js学習静的リソースサーバー
Full が表示されます。コード: https://github.com/Samaritan89/static-server/tree/v2

プログラミング関連の知識については、プログラミング教育をご覧ください。 !

以上がNode.js学習静的リソースサーバーの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

関連ラベル:
ソース:segmentfault.com
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
最新の問題
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!