Skip to content

Instantly share code, notes, and snippets.

@noamtamim
Last active January 3, 2024 15:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save noamtamim/e399f3fa3ade0b1b325cebfecc8d7b10 to your computer and use it in GitHub Desktop.
Save noamtamim/e399f3fa3ade0b1b325cebfecc8d7b10 to your computer and use it in GitHub Desktop.
Simple NodeJS http server that prints requests to stdout
// Usage:
// node httprint.mjs [PORT]
//
// The default port is 3000.
// Prints to stdout the request method, url, headers and body.
// Always returns 200 with an empty JSON object as the body and application/json as the content type.
import { createServer } from "node:http";
const port = process.argv[2] || 3000;
createServer()
.listen(port)
.on("request", (req, res) => {
console.log(req.method, req.url);
console.log(JSON.stringify(req.headers));
let hasBody = false;
req
.on("data", (chunk) => {
hasBody = true;
process.stdout.write(chunk);
})
.on("end", () => {
console.log((hasBody ? "\n" : "") + "----");
res.writeHead(200, { "Content-Type": "application/json" });
res.write("{}");
res.end();
});
})
.on("listening", () => console.log(`Listening on http://localhost:${port}`));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment