ホームページ >ウェブフロントエンド >jsチュートリアル >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 テスト可能

アクセス パスがフォルダーの場合、プログラムはエラーを報告します
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 にアクセスします。ディレクトリ ファイル 
Full が表示されます。コード: https://github.com/Samaritan89/static-server/tree/v2
プログラミング関連の知識については、プログラミング教育をご覧ください。 !
以上がNode.js学習静的リソースサーバーの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。