Skip to content

Instantly share code, notes, and snippets.

@sampathsris
Created October 31, 2023 03:22
Show Gist options
  • Save sampathsris/ed4a135517079b38108e036d42ad115e to your computer and use it in GitHub Desktop.
Save sampathsris/ed4a135517079b38108e036d42ad115e to your computer and use it in GitHub Desktop.
JSON Echo Server in Node.js with no NPM installs
{
"name": "json-echo-server",
"version": "0.1.0",
"description": "Echos the request payload as JSON",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Sampath Sitinamaluwa",
"license": "ISC"
}
const http = require("node:http");
const PORT = process.env.PORT || 8000;
const server = http.createServer((req, res) => {
let raw = "";
req.on('data', chunk => raw += chunk);
req.on('end', () => {
let json;
let error;
try {
console.log(`Parsing: ${raw}`)
json = JSON.parse(raw);
} catch(e) {
error = e.message;
}
res.writeHead(
error ? 400 : 200,
{ 'Content-Type': 'application/json' }
);
res.end(JSON.stringify({ error, json, raw }));
});
});
server.listen(PORT, () => {
console.log(`HTTP Server listening on port ${PORT}`);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment