目录前言基础示例简易 serve 实现arg - 命令行参数读取chalk - 控制台信息输出源码扩展rewrite 和 redirect 的区别?前言 静态资源服务器(Http 服
静态资源服务器(Http 服务器)可以将静态文件(如 js、CSS、图片)等通过 HTTP 协议展现给客户端。本文介绍如何基于 node 实现一个简易的静态资源服务器(类似于 serve)。
const fs = require("node:fs");
const fsp = require("node:fs/promises");
const http = require("node:http");
const server = http.createServer(async (req, res) => {
const stat = await fsp.stat("./index.html");
res.setHeader("content-length", stat.size);
fs.createReadStream("./index.html").pipe(res);
});
server.listen(3000, () => {
console.log("Listening 3000...");
});
在上述示例中,我们创建了一个 http server,并以 stream 的方式返回一个 index.html 文件。其中,分别引入引入了 Node 中的 fs、fsp、http
模块,各个模块的作用如下:
serve 的核心功能非常简单,它以命令行形式指定服务的文件根路径和服务端口,并创建一个 http 服务。
使用 npm 包 arg 读取命令行参数,www.npmjs.com/package/arg。
使用 npm 包 chalk 在控制台输出带有颜色的文字信息,方便调试预览。
// Native - Node built-in module
const fs = require("node:fs");
const fsp = require("node:fs/promises");
const http = require("node:http");
const path = require("node:path");
// Packages
const arg = require("arg");
const chalk = require("chalk");
var config = {
entry: "",
rewrites: [],
redirects: [],
etag: false,
cleanUrls: false,
trailingSlash: false,
symlink: false,
};
const args = arg({
"--port": Number,
"--entry": String,
"--rewrite": Boolean,
"--redirect": Boolean,
"--etag": Boolean,
"--cleanUrls": Boolean,
"--trailingSlash": Boolean,
"--symlink": Boolean,
});
const resourceNotFound = (response, absolutePath) => {
response.statusCode = 404;
fs.createReadStream(path.join("./html", "404.html")).pipe(response);
};
const processDirectory = async (absolutePath) => {
const newAbsolutePath = path.join(absolutePath, "index.html");
try {
const newStat = await fsp.lstat(newAbsolutePath);
return [newStat, newAbsolutePath];
} catch (e) {
return [null, newAbsolutePath];
}
};
const handler = async (request, response, config) => {
// 从 request 中获取 pathname
const pathname = new URL(request.url, `http://${request.headers.host}`)
.pathname;
// 获取绝对路径
let absolutePath = path.resolve(
config["--entry"] || "",
path.join(".", pathname)
);
let statusCode = 200;
let fileStat = null;
// 获取文件状态
try {
fileStat = await fsp.lstat(absolutePath);
} catch (e) {
// console.log(chalk.red(e));
}
if (fileStat?.isDirectory()) {
[fileStat, absolutePath] = await processDirectory(absolutePath);
}
if (fileStat === null) {
return resourceNotFound(response, absolutePath);
}
let headers = {
"Content-Length": fileStat.size,
};
response.writeHead(statusCode, headers);
fs.createReadStream(absolutePath).pipe(response);
};
const startEndpoint = (port, config) => {
const server = http.createServer((request, response) => {
// console.log("request: ", request);
handler(request, response, config);
});
server.on("error", (err) => {
const { code, port } = err;
if (code === "EADDRINUSE") {
console.log(chalk.red(`address already in use [:::${port}]`));
console.log(chalk.green(`Restart server on [:::${port + 1}]`));
startEndpoint(port + 1, entry);
return;
}
process.exit(1);
});
server.listen(port, () => {
console.log(chalk.green(`Open http://localhost:${port}`));
});
};
startEndpoint(args["--port"] || 3000, args);
到此这篇关于基于 Node 实现简易 serve(静态资源服务器)的文章就介绍到这了,更多相关node实现静态资源服务器内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: 基于Node实现简易serve静态资源服务器的示例详解
本文链接: https://www.lsjlt.com/news/152046.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-04-30
2024-04-30
2024-04-30
2024-04-29
2024-04-29
2024-04-29
2024-04-18
2024-04-17
2024-04-11
2024-04-08
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0