64 # 实现一个 http-server

准备工作

上一节实现了通过 commander 的配置获取到用户的参数,下面完成借用 promise 写成类的方法一节没有完成的任务,实现一个 http-server,https://www.npmjs.com/package/http-server,http-server 是一个简单的零配置命令行静态 HTTP 服务器。

需要用到的核心模块

const http = require("http");
const path = require("path");
const url = require("url");
const fs = require("fs").promises;
const { createReadStream, createWriteStream, readFileSync } = require("fs");

需要用到的第三方模块:

  • ejs 用来进行模板渲染
  • mime 用来根据文件扩展名获取 MIME type, 也可以根据 MIME type 获取扩展名。
  • chalk 用来控制台输出着色
  • debug 可以根据环境变量来进行打印
const ejs = require("ejs"); // 服务端读取目录进行渲染
const mime = require("mime");
const chalk = require("chalk");
const debug = require("debug")("server");

安装依赖

npm install ejs@3.1.3 debug@4.1.1 mime@2.4.6 chalk@4.1.0

在这里插入图片描述

配置环境变量

const debug = require("debug")("server");
// 根据环境变量来进行打印 process.env.EDBUG
debug("hello kaimo-http-server");
set DEBUG=server
kaimo-http-server

在这里插入图片描述

代码实现

  1. 将拿到的配置数据开启一个 server

www.js 里面实现

#! /usr/bin/env node

const program = require("commander");
const { version } = require("../package.json");
const config = require("./config.js");
const Server = require("../src/server.js");

program.name("kaimo-http-server");
program.usage("[args]");
program.version(version);

Object.values(config).forEach((val) => {
    if (val.option) {
        program.option(val.option, val.description);
    }
});

program.on("--help", () => {
    console.log("\r\nExamples:");
    Object.values(config).forEach((val) => {
        if (val.usage) {
            console.log("  " + val.usage);
        }
    });
});

// 解析用户的参数
let parseObj = program.parse(process.argv);

let keys = Object.keys(config);

// 最终用户拿到的数据
let resultConfig = {};
keys.forEach((key) => {
    resultConfig[key] = parseObj[key] || config[key].default;
});

// 将拿到的配置数据开启一个 server
console.log("resultConfig---->", resultConfig);
let server = new Server(resultConfig);
server.start();
  1. 实现 server.js,主要的逻辑就是通过核心模块以及第三方模块将用户输入的参数,实现一个 Server 类,里面通过 start 方法开启服务,核心逻辑实现通过路径找到这个文件返回,如果是文件夹处理是否有 index.html 文件,没有的话就通过模板渲染文件夹里目录信息。
// 核心模块
const http = require("http");
const path = require("path");
const url = require("url");
const fs = require("fs").promises;
const { createReadStream, createWriteStream, readFileSync } = require("fs");

// 第三方模块
const ejs = require("ejs"); // 服务端读取目录进行渲染
const mime = require("mime");
const chalk = require("chalk");
const debug = require("debug")("server");
// 根据环境变量来进行打印 process.env.EDBUG
debug("hello kaimo-http-server");

// 同步读取模板
const template = readFileSync(path.resolve(__dirname, "template.ejs"), "utf-8");

class Server {
    constructor(config) {
        this.host = config.host;
        this.port = config.port;
        this.directory = config.directory;
        this.template = template;
    }
    async handleRequest(req, res) {
        let { pathname } = url.parse(req.url);
        // 需要对 pathname 进行一次转义,避免访问中文名称文件找不到问题
        console.log(pathname);
        pathname = decodeURIComponent(pathname);
        console.log(pathname);
        // 通过路径找到这个文件返回
        let filePath = path.join(this.directory, pathname);
        console.log(filePath);
        try {
            // 用流读取文件
            let statObj = await fs.stat(filePath);
            // 判断是否是文件
            if (statObj.isFile()) {
                this.sendFile(req, res, filePath, statObj);
            } else {
                // 文件夹的话就先尝试找找 index.html
                let concatFilePath = path.join(filePath, "index.html");
                try {
                    let statObj = await fs.stat(concatFilePath);
                    this.sendFile(req, res, concatFilePath, statObj);
                } catch (e) {
                    // index.html 不存在就列出目录
                    this.showList(req, res, filePath, statObj, pathname);
                }
            }
        } catch (e) {
            this.sendError(req, res, e);
        }
    }
    // 列出目录
    async showList(req, res, filePath, statObj, pathname) {
        // 读取目录包含的信息
        let dirs = await fs.readdir(filePath);
        console.log(dirs, "-------------dirs----------");
        try {
            let parseObj = dirs.map((item) => ({
                dir: item,
                href: path.join(pathname, item) // url路径拼接自己的路径
            }));
            // 渲染列表:这里采用异步渲染
            let templateStr = await ejs.render(this.template, { dirs: parseObj }, { async: true });
            console.log(templateStr, "-------------templateStr----------");
            res.setHeader("Content-type", "text/html;charset=utf-8");
            res.end(templateStr);
        } catch (e) {
            this.sendError(req, res, e);
        }
    }
    // 读取文件返回
    sendFile(req, res, filePath, statObj) {
        // 设置类型
        res.setHeader("Content-type", mime.getType(filePath) + ";charset=utf-8");
        // 读取文件进行响应
        createReadStream(filePath).pipe(res);
    }
    // 专门处理错误信息
    sendError(req, res, e) {
        debug(e);
        res.statusCode = 404;
        res.end("Not Found");
    }
    start() {
        const server = http.createServer(this.handleRequest.bind(this));
        server.listen(this.port, this.host, () => {
            console.log(chalk.yellow(`Starting up kaimo-http-server, serving ./${this.directory.split("\\").pop()}\r\n`));
            console.log(chalk.green(`       http://${this.host}:${this.port}`));
        });
    }
}

module.exports = Server;
  1. 模板 template.ejs 的代码
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>列表模板</title>
    </head>

    <body>
        <% dirs.forEach(item=> { %>
        <li>
            <a href="<%=item.href%>"><%=item.dir%></a>
        </li>
        <% }) %>
    </body>
</html>

实现效果

控制台我们输入下面命令启动一个端口为 4000 的服务

kaimo-http-server --port 4000

我们访问 http://localhost:4000/,可以看到

在这里插入图片描述

我们在进入 public 文件,里面有 index.html 文件

在这里插入图片描述

点击 public 目录进入 http://localhost:4000/public,可以看到返回了 index.html 页面

在这里插入图片描述

我们在进入 public2 文件,里面没有 index.html 文件

在这里插入图片描述

点击 public2 目录进入 http://localhost:4000/public2,看到的就是列表

在这里插入图片描述

我们可以点击任何的文件查看:比如 凯小默.txt

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/61068.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

pycharm打开terminal报错

Pycharm打开终端报错如何解决&#xff1f;估计是终端启动conda不顺利&#xff0c;需要重新设置路径。参考以下文章的做法即可。 Windows下Pycharm中Terminal无法进入conda环境和Python Console 不能使用 给pycharm中Terminal 添加新的shell&#xff0c;才可以使用conda环境 W…

HDFS中的Federation联邦机制

HDFS中的Federation联邦机制 当前HDFS体系架构--简介局限性 联邦Federation架构简介好处配置示例 当前HDFS体系架构–简介 当前的HDFS结构有两个主要的层&#xff1a; 命名空间&#xff08;namespace&#xff09; 由文件&#xff0c;块和目录组成的统一抽象的目录树结构。由n…

2配置篇:基础功能配置

前言 在上一章节中,我们学习了 NestJS CLI 的用法,得到了一套基础的项目工程。最开始做项目对比的时候也提到过,NestJS 作为一款自定义程度较高的框架,CLI 直接提供的基础功能虽然并不完善,但同时也为开发者提供了非常多的内置或配套的功能例如高速缓存、日志拦截、过滤器…

SocialFi 的开发中如何利用 NFTScan API 获取 NFT 数据

SocialFi 作为社交媒体与 Web3 的创新融合&#xff0c;致力于构建更加开放去中心化的社交平台。它赋能用户拥有数据控制权、实现内容价值&#xff0c;并通过代币经济建立起激励与治理机制&#xff0c;这正是 Web3 社交的独特魅力所在。SocialFi 为我们描绘了一个更加用户驱动、…

回顾 OWASP 机器学习十大风险

日复一日&#xff0c;越来越多的机器学习 (ML) 模型正在开发中。机器学习模型用于查找训练数据中的模式&#xff0c;可以产生令人印象深刻的检测和分类能力。机器学习已经为人工智能的许多领域提供了动力&#xff0c;包括情感分析、图像分类、面部检测、威胁情报等。 数十亿美…

《零基础入门学习Python》第076讲:GUI的终极选择:Tkinter13

这节课我们来学习 Tkinter 的布局管理器&#xff0c;那什么是布局管理器呢&#xff1f;说白了&#xff0c;就是用于管理你的组件如何排列。Tkinter 提供了 3 大布局管理器&#xff1a;pack、grid 和 place。 pack 是按添加顺序排列组件grid 是按行/列形式排列组件place 则允许…

秋招算法备战第37天 | 738.单调递增的数字、968.监控二叉树、贪心算法总结

738. 单调递增的数字 - 力扣&#xff08;LeetCode&#xff09; 这个问题是关于找到一个小于或等于给定数字n的最大单调递增数字。 我们可以将数字n转换为字符数组&#xff0c;然后从左到右扫描&#xff0c;寻找第一个违反单调递增条件的位置。一旦找到这样的位置&#xff0c;…

uni-app:实现列表单选功能

效果图&#xff1a; 核心解析&#xff1a; 一、 <view class"item_all" v-for"(item, index) in info" :key"index"><view classposition parameter-info text-over :classitem.checked?"checked_parameter":""…

在java中操作redis_Data

1.引入依赖 <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency> 2.配置Redis数据源 redis:host: ${sky.redis.host}port: ${sky.redis.port}password: ${sk…

驱动工作原理

驱动原理 在Linux操作系统中&#xff0c;硬件驱动程序中实现对硬件直接操作&#xff0c;而用户空间&#xff0c;通过通用的系统调用接口&#xff08;open() 打开相应的驱动设备,ioctl()控制相应的功能等&#xff09;&#xff0c;实现对硬件操作&#xff0c;应用程序没有直接操作…

EdgeBox_tx1_A200 PyTorch v1.9.0 环境部署

大家好&#xff0c;我是虎哥&#xff0c;今天远程帮助几个小伙伴在A200 控制器上安装PyTorch v1.9.0 torchvision v0.10.0&#xff0c;中间也是经历了很多波折&#xff0c;当然&#xff0c;大部分是网络问题和版本适配问题&#xff0c;所以完事后&#xff0c;将自己完整可用的过…

分布式Redis详解

目录 前言安装redis的俩种方法Redis 与 MySQL的区别Redis可以实现那些功能Redis常用的数据类型有序列表的底层是如何实现的?什么是跳跃表 Redis在Spring中的使用 前言 Redis我们最近学习必备工具之一了, 接下来我们将讲解Redis的简单应用 ,以及相关原理 安装redis的俩种方法…

20230802-下载并安装android-studio

下载 android-studio 安装包 https://developer.android.google.cn/studio/ 安装android-studio 双击安装包 D:\Android Studio

基于 Flink Paimon 实现 Streaming Warehouse 数据一致性管理

摘要&#xff1a;本文整理自字节跳动基础架构工程师李明&#xff0c;在 Apache Paimon Meetup 的分享。本篇内容主要分为四个部分&#xff1a; 背景 方案设计 当前进展 未来规划 点击查看原文视频 & 演讲PPT 一、背景 ​ 早期的数仓生产体系主要以离线数仓为主&#xf…

vue-baidu-map-3x 使用记录

在 Vue3 TypeScript 项目中&#xff0c;为了采用 标签组件 的方式&#xff0c;使用百度地图组件&#xff0c;冲浪发现了一个开源库 ovo&#xff0c;很方便&#xff01;喜欢的朋友记得帮 原作者 点下 star ~ vue-baidu-map-3xbaidu-map的vue3/vue2版本&#xff08;支持v2.0、v…

论文笔记:SUPERVISED CONTRASTIVE REGRESSION

2022arxiv的论文&#xff0c;没有中&#xff0c;但一作是P大图班本MIT博&#xff0c;可信度应该还是可以的 0 摘要 深度回归模型通常以端到端的方式进行学习&#xff0c;不明确尝试学习具有回归意识的表示。 它们的表示往往是分散的&#xff0c;未能捕捉回归任务的连续性质。…

MCU的类型和应用领域简介

MCU&#xff08;Microcontroller Unit&#xff09;根据存储器类型可分为无片内ROM型和带片内ROM型。无片内ROM型的芯片需要外接EPROM才能应用&#xff0c;而带片内ROM型则有不同的子类型&#xff0c;如片内EPROM型、MASK片内掩模ROM型和片内Flash型。 MCU还可以按照用途分为通…

策略模式——算法的封装与切换

1、简介 1.1、概述 在软件开发中&#xff0c;常常会遇到这种情况&#xff0c;实现某一个功能有多条途径。每一条途径对应一种算法&#xff0c;此时可以使用一种设计模式来实现灵活地选择解决途径&#xff0c;也能够方便地增加新的解决途径。为了适应算法灵活性而产生的设计模…

【分布式应用】ELK企业级日志分析系统

目录 一、ELK 简介 1.1 ELK各组件介绍 ElasticSearch&#xff1a; Kiabana&#xff1a; Logstash&#xff1a; 1.2 可以添加的其它组件&#xff1a; Filebeat&#xff1a; 缓存/消息队列&#xff08;redis、kafka、RabbitMQ等&#xff09;&#xff1a; Fluentd&#xf…

向表中随机插入字符串数据

已知表 向该表中插入指定次数的随机字符串&#xff1a; 代码如下: DROP PROCEDURE sc //CREATE PROCEDURE sc(num INT) BEGIN DECLARE str VARCHAR(26) DEFAULT "abcdefghijklmnopqrstuvwxyz"; DECLARE cnt INT DEFAULT 0; DECLARE startIndex INT DEFAULT 1; DE…
最新文章