Created
October 31, 2023 03:22
-
-
Save sampathsris/ed4a135517079b38108e036d42ad115e to your computer and use it in GitHub Desktop.
JSON Echo Server in Node.js with no NPM installs
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
{ | |
"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" | |
} |
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
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