2
Deno 简单测试服务器
source link: https://segmentfault.com/a/1190000040514730
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Deno 简单测试服务器
发布于 8 月 14 日
有时候会需要临时起一个简单的服务器,用来测试查看请求信息。刚好用 Deno
官网的例子改一个。用 Node.js
写其实也一样方便。
deno run --allow-net server.ts
import { parse } from "https://deno.land/[email protected]/flags/mod.ts";
import { serve } from "https://deno.land/[email protected]/http/server.ts";
interface Args {
_: string[];
// --prot
port?: number;
// --on-headers
"on-headers"?: boolean;
}
const args = <Args>parse(Deno.args); // 获取启动参数
/**
* 启动 deno run --allow-net server.ts
*/
const PORT = args.port ? args.port : 7070;
const server = serve({ port: PORT });
console.log(
`HTTP webserver running. Access it at: http://localhost:${PORT}/`
);
for await (const request of server) {
if (request.url !== "/favicon.ico") {
const time = formatTimestamp(new Date().getTime());
console.log("");
console.log(
`\x1b[32m[${time}]\x1b[0m method: ${request.method} url: ${request.url}`
);
if (args["on-headers"]) console.log(`headers: `, request.headers);
}
request.respond({ status: 200, body: "ok" });
}
/**
* 时间戳格式化
* @param timestamp
* @param options
* @returns
*/
function formatTimestamp(
timestamp: number,
options?: {
dateSection: boolean;
timeSection: boolean;
dateSign: string;
timeSign: string;
linkSign: string;
places: number;
}
) {
const $d = new Date(
timestamp.toString().length === 10 ? timestamp * 1000 : timestamp
);
if ($d.toString() === "Invalid Date") return "Invalid Date";
const {
dateSection = true,
timeSection = true,
dateSign = "-",
timeSign = ":",
linkSign = " ",
places = 2,
} = options || {};
const padStart = (string: number, length = places) => {
const s = String(string);
if (!s || s.length >= length) return string;
return `${Array(length + 1 - s.length).join("0")}${string}`;
};
const $y = $d.getFullYear(),
$M = padStart($d.getMonth() + 1),
$D = padStart($d.getDate()),
$H = padStart($d.getHours()),
$m = padStart($d.getMinutes()),
$s = padStart($d.getSeconds());
let text = "";
if (dateSection) text += `${$y}${dateSign}${$M}${dateSign}${$D}`;
if (timeSection) text += `${linkSign}${$H}${timeSign}${$m}${timeSign}${$s}`;
return text;
}
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK