From e740cadcad00e63a3286b4de85bedc68b3c71405 Mon Sep 17 00:00:00 2001 From: Lxy Date: Tue, 7 Dec 2021 20:51:06 +0800 Subject: [PATCH] add resource server --- doric-cli/src/dev.ts | 2 ++ doric-cli/src/resourceServer.ts | 50 +++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 doric-cli/src/resourceServer.ts diff --git a/doric-cli/src/dev.ts b/doric-cli/src/dev.ts index 49f15526..5b705371 100644 --- a/doric-cli/src/dev.ts +++ b/doric-cli/src/dev.ts @@ -7,6 +7,7 @@ import { mergeMap } from "./actions"; import os from "os"; import qrcode from "qrcode-terminal"; import keypress from "keypress"; +import { createResServer } from "./resourceServer" function getIPAdress() { const ret: string[] = []; @@ -119,6 +120,7 @@ export default async function dev() { console.log(`IP:${e}`); qrcode.generate(e, { small: true }); }); + createResServer(); } diff --git a/doric-cli/src/resourceServer.ts b/doric-cli/src/resourceServer.ts new file mode 100644 index 00000000..0e8726fa --- /dev/null +++ b/doric-cli/src/resourceServer.ts @@ -0,0 +1,50 @@ +import fs from "fs" +import path from "path" +import http from 'http'; +import { IncomingMessage, ServerResponse } from "http"; +export async function createResServer() { + const port = 7778; + const server = http.createServer(); + server.listen(port); + console.log(`Resource server is listening on port ${port} !`.green); + server.on('request', (request: IncomingMessage, response: ServerResponse) => { + const { url } = request; + if (url) { + try { + const pathArr = url.split("/"); + const resName = pathArr[pathArr.length - 1]; + const dirPath = path.join(process.cwd(), url.replace(`/${resName}`, "")); + const fileRealName = findResRealName(dirPath, resName); + const resourcePath = path.join(dirPath, `${fileRealName}`); + if (fs.existsSync(resourcePath)) { + const data = fs.readFileSync(resourcePath); + response.write(data); + response.end(); + } else { + response.setHeader("content-type", "text/html; charset=utf-8"); + console.error(`Resources ${resName} do not exist !`.red) + response.end(`Resources ${resName} do not exist !`); + } + } catch (error) { + response.setHeader("content-type", "text/html; charset=utf-8"); + console.error(`Server internal error`.red) + response.end("Server internal error" + error); + } + } else { + response.setHeader("content-type", "text/html; charset=utf-8"); + console.error(`url is undefined`.red) + response.end("url is undefined"); + } + }); + + function findResRealName(dirPath: string, fileName: string) { + let fileFinalName = ""; + const stats = fs.readdirSync(dirPath); + for (let stat of stats) { + if (stat.startsWith(`${fileName}.`) || stat === fileName) { + fileFinalName = stat; + return fileFinalName; + } + } + } +}