Skip to content

Instantly share code, notes, and snippets.

@AliSawari
Last active January 17, 2024 15:42
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 AliSawari/f9d40a8ad779128adc2dedbef6ade662 to your computer and use it in GitHub Desktop.
Save AliSawari/f9d40a8ad779128adc2dedbef6ade662 to your computer and use it in GitHub Desktop.
Simple Body Parser in Node.js
const { createServer } = require('http');
const server = createServer((request, response) => {
// by default assign maximum of 2KB for Body size if there's no Content-Length
let size = Number(request.headers['content-length']) || 2048;
let bodyData = Buffer.alloc(size);
request.on('data', data => {
for (let x = 0; x < size; x++) {
bodyData[x] = data[x];
}
})
request.on('end', () => {
const raw = bodyData.toString();
const realBody = JSON.parse(raw);
console.log(realBody);
// Empty the Buffer
bodyData = null;
})
response.statusCode = 200;
response.end("OK");
});
server.listen(3000, () => console.log("UP"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment