From be8aadbcd89cbcfe3643d53a451d985a56d81386 Mon Sep 17 00:00:00 2001 From: Cristopher <32661241+Namchee@users.noreply.github.com> Date: Fri, 15 Nov 2024 08:52:52 +0700 Subject: [PATCH] docs: add body-parser (#161) --- docs/modules/README.md | 1 + docs/modules/body-parser.md | 51 +++++++++++++++++++++++++++++++++++++ manifests/preferred.json | 6 +++++ 3 files changed, 58 insertions(+) create mode 100644 docs/modules/body-parser.md diff --git a/docs/modules/README.md b/docs/modules/README.md index a016afd..3c7955f 100644 --- a/docs/modules/README.md +++ b/docs/modules/README.md @@ -14,6 +14,7 @@ ESLint plugin. - [`@jsdevtools/ez-spawn`](./process-exec.md) - [`bluebird` / `q`](./bluebird-q.md) +- [`body-parser`](./body-parser.md) - [`buf-compare`](./buf-compare.md) - [`buffer-equal` / `buffer-equals`](./buffer-equal.md) - [`cpx`](./cpx.md) diff --git a/docs/modules/body-parser.md b/docs/modules/body-parser.md new file mode 100644 index 0000000..f869278 --- /dev/null +++ b/docs/modules/body-parser.md @@ -0,0 +1,51 @@ +# Body-parser + +`body-parser` can be replaced with more modern alternatives which are both lighter and faster. + +# Alternatives + +## Native Implementation + +For simple use cases, you can implement a minimal body parser in vanilla JavaScript: + +```js +const sizeLimit = 10 * 1024; // limit body size to 10kB +req.body = {}; + +await new Promise(function(res, rej) { + let buffers = []; + let size = 0; + + // parse each chunk and append them into Buffer array + req.on('data', chunk => { + size += chunk.length; + if (size > sizeLimit) { + return rej(new Error('Size limit')); + } + + buffers.push(chunk); + }); + + req.on('end', () => res(buffers)); +}) +.then(function(buffers) { + if (!buffers.length) return; + + try { + req.body = JSON.parse(Buffer.concat(buffers).toString()); + } catch (err) { + return Promise.reject(new Error('Invalid JSON: ' + err.message)); + } +}); +``` + +Do note that the above implementation lacks sophisticated features such as better error handling, timeouts, flexible size limits, etc. + + +## milliparsec + +`milliparsec` a modern `body-parser` alternative that supports `async / await`, lighter (8 kB vs 62.6 kB for `body-parser`), and [30% faster](https://github.com/tinyhttp/milliparsec/blob/master/bench/index.md) + +[Project Page](https://github.com/tinyhttp/milliparsec) +[npm](https://www.npmjs.com/package/milliparsec) + diff --git a/manifests/preferred.json b/manifests/preferred.json index a761909..c92052d 100644 --- a/manifests/preferred.json +++ b/manifests/preferred.json @@ -12,6 +12,12 @@ "docPath": "bluebird-q", "category": "preferred" }, + { + "type": "documented", + "moduleName": "body-parser", + "docPath": "body-parser", + "category": "preferred" + }, { "type": "documented", "moduleName": "buf-compare",