有时候会需要临时起一个简单的服务器,用来测试查看请求信息。刚好用 Deno
官网的例子改一个。用 Node.js
写其实也一样方便。
启动命令
deno run --allow-net server.ts
import { parse } from "https://deno.land/std@0.104.0/flags/mod.ts";
import { serve } from "https://deno.land/std@0.104.0/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;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。