Skip to content

Instantly share code, notes, and snippets.

@zhzLuke96
Created January 2, 2024 11:44
Show Gist options
  • Save zhzLuke96/240d757187104e5d3e7df982b88d78cb to your computer and use it in GitHub Desktop.
Save zhzLuke96/240d757187104e5d3e7df982b88d78cb to your computer and use it in GitHub Desktop.
// debug server
import http from "http";
import { URL } from "url";
import { inspect } from "util";
const readBody = (req: http.IncomingMessage) =>
new Promise<Buffer>((resolve, reject) => {
const chunks: Buffer[] = [];
req.on("data", (chunk) => chunks.push(chunk));
req.on("end", () => resolve(Buffer.concat(chunks)));
req.on("error", reject);
});
http
.createServer(async (req, res) => {
const url = new URL(req.url!, "http://localhost");
const { hostname, pathname, searchParams } = url;
const { method, headers } = req;
const body = await readBody(req);
const bodyStr = body.toString();
const bodyStrTruncated =
bodyStr.length > 100 ? bodyStr.slice(0, 100) + "..." : bodyStr;
console.log(
`${method} ${hostname}${pathname}${searchParams} ${inspect(
headers
)} ${bodyStrTruncated}`
);
res.writeHead(200, { "Content-Type": "text/plain" });
res.end(body);
})
.listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment