Last active
January 3, 2024 15:13
-
-
Save noamtamim/e399f3fa3ade0b1b325cebfecc8d7b10 to your computer and use it in GitHub Desktop.
Simple NodeJS http server that prints requests to stdout
This file contains 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
// 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