Created
January 2, 2024 11:44
-
-
Save zhzLuke96/240d757187104e5d3e7df982b88d78cb to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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