国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

64 # 實(shí)現(xiàn)一個 http-server

這篇具有很好參考價(jià)值的文章主要介紹了64 # 實(shí)現(xiàn)一個 http-server。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。

準(zhǔn)備工作

上一節(jié)實(shí)現(xiàn)了通過 commander 的配置獲取到用戶的參數(shù),下面完成借用 promise 寫成類的方法一節(jié)沒有完成的任務(wù),實(shí)現(xiàn)一個 http-server,https://www.npmjs.com/package/http-server,http-server 是一個簡單的零配置命令行靜態(tài) HTTP 服務(wù)器。

需要用到的核心模塊

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

需要用到的第三方模塊:

  • ejs 用來進(jìn)行模板渲染
  • mime 用來根據(jù)文件擴(kuò)展名獲取 MIME type, 也可以根據(jù) MIME type 獲取擴(kuò)展名。
  • chalk 用來控制臺輸出著色
  • debug 可以根據(jù)環(huán)境變量來進(jìn)行打印
const ejs = require("ejs"); // 服務(wù)端讀取目錄進(jìn)行渲染
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

64 # 實(shí)現(xiàn)一個 http-server,Node / Node 框架,前端工程架構(gòu),http-server

配置環(huán)境變量

const debug = require("debug")("server");
// 根據(jù)環(huán)境變量來進(jìn)行打印 process.env.EDBUG
debug("hello kaimo-http-server");
set DEBUG=server
kaimo-http-server

64 # 實(shí)現(xiàn)一個 http-server,Node / Node 框架,前端工程架構(gòu),http-server

代碼實(shí)現(xiàn)

  1. 將拿到的配置數(shù)據(jù)開啟一個 server

www.js 里面實(shí)現(xiàn)

#! /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);
        }
    });
});

// 解析用戶的參數(shù)
let parseObj = program.parse(process.argv);

let keys = Object.keys(config);

// 最終用戶拿到的數(shù)據(jù)
let resultConfig = {};
keys.forEach((key) => {
    resultConfig[key] = parseObj[key] || config[key].default;
});

// 將拿到的配置數(shù)據(jù)開啟一個 server
console.log("resultConfig---->", resultConfig);
let server = new Server(resultConfig);
server.start();
  1. 實(shí)現(xiàn) server.js,主要的邏輯就是通過核心模塊以及第三方模塊將用戶輸入的參數(shù),實(shí)現(xiàn)一個 Server 類,里面通過 start 方法開啟服務(wù),核心邏輯實(shí)現(xiàn)通過路徑找到這個文件返回,如果是文件夾處理是否有 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"); // 服務(wù)端讀取目錄進(jìn)行渲染
const mime = require("mime");
const chalk = require("chalk");
const debug = require("debug")("server");
// 根據(jù)環(huán)境變量來進(jìn)行打印 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 進(jìn)行一次轉(zhuǎn)義,避免訪問中文名稱文件找不到問題
        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) {
        // 設(shè)置類型
        res.setHeader("Content-type", mime.getType(filePath) + ";charset=utf-8");
        // 讀取文件進(jìn)行響應(yīng)
        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>

實(shí)現(xiàn)效果

控制臺我們輸入下面命令啟動一個端口為 4000 的服務(wù)

kaimo-http-server --port 4000

我們訪問 http://localhost:4000/,可以看到

64 # 實(shí)現(xiàn)一個 http-server,Node / Node 框架,前端工程架構(gòu),http-server

我們在進(jìn)入 public 文件,里面有 index.html 文件

64 # 實(shí)現(xiàn)一個 http-server,Node / Node 框架,前端工程架構(gòu),http-server

點(diǎn)擊 public 目錄進(jìn)入 http://localhost:4000/public,可以看到返回了 index.html 頁面

64 # 實(shí)現(xiàn)一個 http-server,Node / Node 框架,前端工程架構(gòu),http-server

我們在進(jìn)入 public2 文件,里面沒有 index.html 文件

64 # 實(shí)現(xiàn)一個 http-server,Node / Node 框架,前端工程架構(gòu),http-server

點(diǎn)擊 public2 目錄進(jìn)入 http://localhost:4000/public2,看到的就是列表

64 # 實(shí)現(xiàn)一個 http-server,Node / Node 框架,前端工程架構(gòu),http-server

我們可以點(diǎn)擊任何的文件查看:比如 凱小默.txt

64 # 實(shí)現(xiàn)一個 http-server,Node / Node 框架,前端工程架構(gòu),http-server文章來源地址http://www.zghlxwxcb.cn/news/detail-635700.html

到了這里,關(guān)于64 # 實(shí)現(xiàn)一個 http-server的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • 73 # 發(fā)布自己的 http-server 到 npm

    73 # 發(fā)布自己的 http-server 到 npm

    1、添加 .npmignore 文件,忽略不需要的文件 2、去官網(wǎng)https://www.npmjs.com/檢查自己的包名是否被占用 3、切換到官方源,然后檢查確認(rèn) 4、登錄 npm 賬號 5、發(fā)布 6、查看發(fā)布情況,發(fā)布成功之后,等一會,我們就能看到自己的包在 npm 上了 7、更新版本,我們添加一個 README.md 文件

    2024年02月11日
    瀏覽(20)
  • 通過 http-server 運(yùn)行剛打包出來的腳手架項(xiàng)目

    通過 http-server 運(yùn)行剛打包出來的腳手架項(xiàng)目

    這里 我打包了自己的vue項(xiàng)目 react其實(shí)也一樣 如果我直接 打開打包出來的 dist 下面的index.html 會出現(xiàn)白屏資源找不到 或者跨域等問題 這個問題其實(shí)配個nginx也能解決 但是其實(shí)如果只是想做個測試 nginx就太麻煩了 我們可以通過npm指令 全局安裝一個http-server 終端執(zhí)行 安裝好依賴

    2024年02月09日
    瀏覽(22)
  • http-server使用,啟動本地服務(wù)器 & 使用serve包本地啟動

    http-server使用,啟動本地服務(wù)器 & 使用serve包本地啟動

    http-server使用,啟動本地服務(wù)器 使用serve包本地啟動 直接打開html文件,跨域不渲染圖片 1、簡介 官網(wǎng):https://github.com/http-party/http-server http-server是一個簡單的零配置命令行 http服務(wù)器 。 它足夠強(qiáng)大,足以用于生產(chǎn)用途,但它既簡單又易于破解,可用于測試,本地開發(fā)和學(xué)習(xí)。

    2024年02月02日
    瀏覽(30)
  • 如何使用Node.js快速創(chuàng)建HTTP服務(wù)器并實(shí)現(xiàn)公網(wǎng)訪問本地Server

    如何使用Node.js快速創(chuàng)建HTTP服務(wù)器并實(shí)現(xiàn)公網(wǎng)訪問本地Server

    Node.js 是能夠在服務(wù)器端運(yùn)行 JavaScript 的開放源代碼、跨平臺運(yùn)行環(huán)境。Node.js 由 OpenJS Foundation(原為 Node.js Foundation,已與 JS Foundation 合并)持有和維護(hù),亦為 Linux 基金會的項(xiàng)目。Node.js 采用 Google 開發(fā)的 V8 運(yùn)行代碼,使用事件驅(qū)動、非阻塞和異步輸入輸出模型等技術(shù)來提高

    2024年01月15日
    瀏覽(96)
  • java基礎(chǔ) - 實(shí)現(xiàn)一個簡單的Http接口功能自動化測試框架(HttpClient + TestNG)

    java基礎(chǔ) - 實(shí)現(xiàn)一個簡單的Http接口功能自動化測試框架(HttpClient + TestNG)

    已知現(xiàn)在已經(jīng)用Spring boot框架搭建了一個簡單的web服務(wù),并且有現(xiàn)成的Controller來處理http請求,以之前搭建的圖書管理服務(wù)為例,BookController的源碼如下: 在搭建一個Http接口功能自動化測試框架之前,我們需要思考幾個問題: 1、http請求的發(fā)送,使用什么實(shí)現(xiàn)? 2、接口返回的

    2024年02月05日
    瀏覽(28)
  • window中安裝Apache http server(httpd-2.4.58-win64-VS17)

    window中安裝Apache http server(httpd-2.4.58-win64-VS17)

    1、下載windows版本的的httpd, https://httpd.apache.org/docs/current/platform/windows.html#down 這里選擇的是Apache Lounge編譯的版本 https://www.apachelounge.com/download/ 2、解壓到指定目錄,這里解壓到D盤根目錄,得到D:Apache24 3、修改配置文件http.conf 4、修改之后,檢測配置文件是否有語法錯誤 語法

    2024年01月20日
    瀏覽(22)
  • 前端使用node.js連接sql.server數(shù)據(jù)庫教程

    前端使用node.js連接sql.server數(shù)據(jù)庫教程

    最近項(xiàng)目中要用到node寫接口然后連接公司現(xiàn)有的sql.server數(shù)據(jù)庫,再把執(zhí)行結(jié)果返回給前端(還是我),因?yàn)橹耙恢弊銮岸诉@塊,后端這方面不是很懂,花了很長的時(shí)間終于研究出來了(還是太菜了,走了很多彎路),所以寫個博客,一是復(fù)習(xí)鞏固,二是給其他有需要的小伙伴一個參考,盡量

    2024年02月11日
    瀏覽(27)
  • 前端項(xiàng)目部署自動檢測更新后通知用戶刷新頁面(前端實(shí)現(xiàn),技術(shù)框架vue、js、webpack)——方案一:編譯項(xiàng)目時(shí)動態(tài)生成一個記錄版本號的文件

    前端項(xiàng)目部署自動檢測更新后通知用戶刷新頁面(前端實(shí)現(xiàn),技術(shù)框架vue、js、webpack)——方案一:編譯項(xiàng)目時(shí)動態(tài)生成一個記錄版本號的文件

    當(dāng)我們重新部署前端項(xiàng)目的時(shí)候,如果用戶一直停留在頁面上并未刷新使用,會存在功能使用差異性的問題,因此,當(dāng)前端部署項(xiàng)目后,需要提醒用戶有去重新加載頁面。 vue、js、webpack 編譯項(xiàng)目時(shí)動態(tài)生成一個記錄版本號的文件 輪詢(20s、自己設(shè)定時(shí)間)這個文件,判斷版

    2024年02月02日
    瀏覽(57)
  • json-server Node.js 服務(wù),前端模擬后端提供json接口服務(wù)

    json-server Node.js 服務(wù),前端模擬后端提供json接口服務(wù)

    json-server Node.js 服務(wù),前端模擬后端提供json接口服務(wù) 背景: ? ?前后端分離的項(xiàng)目,如果前端寫頁面的話,必須的后端提供接口文件,作為前端等待時(shí)間太久,不便于開發(fā)進(jìn)行,如果前端寫的過程中自己搭建一個簡要的后端的json服務(wù)接口,就是可以快速進(jìn)行開發(fā)事項(xiàng)的進(jìn)行,

    2024年02月16日
    瀏覽(24)
  • 使用node.js給前端發(fā)送一個圖像驗(yàn)證碼

    相信寫過node的小伙伴都對此有相關(guān)了解 首先導(dǎo)入需要的包(//后有解釋) const mysql = require(\\\"mysql\\\"); ? //用于創(chuàng)建和管理 MySQL 連接池。 const express = require(\\\"express\\\");//用于構(gòu)建 Web 應(yīng)用程序。 const app = express(); const interface = require(\\\"./interface\\\"); const bodyParser = require(\\\"body-parser\\\"); //用于

    2024年01月17日
    瀏覽(28)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包