Skip to content

Commit

Permalink
docs: add body-parser (#161)
Browse files Browse the repository at this point in the history
  • Loading branch information
Namchee authored Nov 15, 2024
1 parent 7dea6e8 commit be8aadb
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
1 change: 1 addition & 0 deletions docs/modules/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
51 changes: 51 additions & 0 deletions docs/modules/body-parser.md
Original file line number Diff line number Diff line change
@@ -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)

6 changes: 6 additions & 0 deletions manifests/preferred.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@
"docPath": "bluebird-q",
"category": "preferred"
},
{
"type": "documented",
"moduleName": "body-parser",
"docPath": "body-parser",
"category": "preferred"
},
{
"type": "documented",
"moduleName": "buf-compare",
Expand Down

0 comments on commit be8aadb

Please sign in to comment.