parsec 🌌
Tiniest body parser ever for Node.js.
It puts all the data into req.body
so you don't have to create a separate array for it.
parsec is a part of tinyhttp ecosystem.
Features 👀
- works with Node 13+ ESM and CommonJS 🚀
- built with
async
/ await
⏩ - JSON / raw / urlencoded / text data support 🛠
- tiny package size (879B) 📦
- no dependencies 🔥
- tinyhttp, Koa and Express support
Installation 🔄
pnpm i body-parsec
yarn add body-parsec
npm i body-parsec
Usage ⏩
Basic example 🖐
Use a middleware inside a server:
import { createServer } = from 'http'
import { json } from 'body-parsec'
createServer(async (req, res) => {
const parsedData = await json()(req)
console.log(parsedData)
res.setHeader('Content-Type', 'application/json')
res.end(req.body.hello)
}).listen(80)
Then try to make a request to our server:
curl -d '{ "hello": "world" }' localhost
After sending a request, it should output world
.
Parsec and web frameworks 💻
import { App } from '@tinyhttp/app'
import { urlencoded } from 'body-parsec'
const app = new App()
app.use(urlencoded()).post('/', (req, res) => {
res.send(req.body)
})
app.listen(3000, () => console.log(`Started on http://localhost:3000`))
Express
import Express from 'express'
import { urlencoded } from 'body-parsec'
const app = Express()
app.use(urlencoded())
app.get('/', (req, res) => {
res.send(`
<form method="POST" action="/" enctype="application/x-www-form-urlencoded">
<input name="name" />
</form>
`)
})
app.post('/', (req, res) => {
res.send(`Hello ${req.body.name}!`)
})
app.listen(3000, () => console.log(`Running on http://localhost:3000`))
Koa
import Koa from 'koa'
import { json, CtxWithBody } from 'body-parsec/koa'
const app = new Koa()
app.use(json())
app.use((ctx: CtxWithBody) => {
if (ctx.method === 'POST') {
ctx.type = 'application/json'
ctx.body = ctx.req.body
}
})
app.listen(3000, () => console.log(`Running on http://localhost:3000`))
API 📦
parsec.raw(req)
Minimal body parsing without any urlencodedatting (even without converting to string):
await parsec.raw()(req)
res.end(req.body)
parsec.text(req)
Converts request body to string.
await parsec.text()(req)
res.end(req.body)
parsec.custom(req, fn)
You can use parsec
as a a handler for IncomingMessage
with a custom urlencodedatter.
Here we make a request body upper case:
await parsec.custom(req, (data) => data.toUpperCase())
res.end(req.body)
parsec.json(req)
Parses request body using JSON.parse
.
await parsec.json()(req)
res.end(req.body.hello)
parsec.urlencoded(req)
Parses request body using querystring.parse
.
await parsec.urlencoded()(req)
res.end(req.body.username)
What is "parsec"?
The parsec (symbol: pc) is a unit of length used to measure large distances to astronomical objects outside the Solar System.