*[[`ad6b34d`](http://github.com/cojs/co-body/commit/ad6b34d72886001215a7ed71861b63dbddbbf40b)] - feat: use async function (#65) (Haoliang Gao <<sakura9515@gmail.com>>)
5.2.0 / 2018-05-02
==================
**features**
*[[`f65a2d8`](http://github.com/cojs/co-body/commit/f65a2d8f7ebf4426138035af6d7e7f02272441f2)] - feat: impl text parser support encoding: false (#64) (killa <<killa123@126.com>>)
5.1.1 / 2017-03-24
==================
* fix: getOptions change to clone
* fix: ensure options are independent in each request
5.1.0 / 2017-03-21
==================
* feat: add options to support return raw body (#56)
5.0.3 / 2017-03-19
==================
* fix: ensure inflate in promise chain (#54)
5.0.2 / 2017-03-10
==================
* fix: keep compatibility with qs@4 (#53)
5.0.1 / 2017-03-06
==================
* dpes: qs@6.4.0
5.0.0 / 2017-03-02
==================
* deps: upgrade qs to 6.x (#52)
4.2.0 / 2016-05-05
==================
* test: test on node 4, 5, 6
* feat: Added support for request body inflation
4.1.0 / 2016-05-05
==================
* feat: form parse support custom qs module
4.0.0 / 2015-08-15
==================
* Switch to Promises instead of thunks
3.1.0 / 2015-08-06
==================
* travis: add v2, v3, remove 0.11
* add custom types options
* use type-is
3.0.0 / 2015-07-25
==================
* Updated dependencies. Added qs options support via queryString option key. (@yanickrochon)
* upgrade qs@4.0.0, raw-body@2.1.2
2.0.0 / 2015-05-04
==================
* json parser support strict mode
1.2.0 / 2015-04-29
==================
* Add JSON-LD as known JSON-Type (@vanthome)
1.1.0 / 2015-02-27
==================
* Fix content-length zero should not parse json
* Bump deps, qs@~2.3.3, raw-body@~1.3.3
* add support for `text/plain`
* json support for `application/json-patch+json`, `application/vnd.api+json` and `application/csp-report`
Parse request bodies with generators inspired by [Raynos/body](https://github.com/Raynos/body).
## Installation
```bash
$ npm install co-body
```
## Options
-`limit` number or string representing the request size limit (1mb for json and 56kb for form-urlencoded)
-`strict` when set to `true`, JSON parser will only accept arrays and objects; when `false` will accept anything `JSON.parse` accepts. Defaults to `true`. (also `strict` mode will always return object).
-`queryString` an object of options when parsing query strings and form data. See [qs](https://github.com/hapijs/qs) for more information.
-`returnRawBody` when set to `true`, the return value of `co-body` will be an object with two properties: `{ parsed: /* parsed value */, raw: /* raw body */}`.
-`jsonTypes` is used to determine what media type **co-body** will parse as **json**, this option is passed directly to the [type-is](https://github.com/jshttp/type-is) library.
-`formTypes` is used to determine what media type **co-body** will parse as **form**, this option is passed directly to the [type-is](https://github.com/jshttp/type-is) library.
-`textTypes` is used to determine what media type **co-body** will parse as **text**, this option is passed directly to the [type-is](https://github.com/jshttp/type-is) library.
more options available via [raw-body](https://github.com/stream-utils/raw-body#getrawbodystream-options-callback):
## Pure JS character encoding conversion [![Build Status](https://travis-ci.org/ashtuchkin/iconv-lite.svg?branch=master)](https://travis-ci.org/ashtuchkin/iconv-lite)
* Doesn't need native code compilation. Works on Windows and in sandboxed environments like [Cloud9](http://c9.io).
* Used in popular projects like [Express.js (body_parser)](https://github.com/expressjs/body-parser),
[Grunt](http://gruntjs.com/), [Nodemailer](http://www.nodemailer.com/), [Yeoman](http://yeoman.io/) and others.
* Faster than [node-iconv](https://github.com/bnoordhuis/node-iconv)(see below for performance comparison).
* Intuitive encode/decode API
* Streaming support for Node v0.10+
*[Deprecated] Can extend Node.js primitives (buffers, streams) to support all iconv-lite encodings.
* In-browser usage via [Browserify](https://github.com/substack/node-browserify)(~180k gzip compressed with Buffer shim included).
See [all supported encodings on wiki](https://github.com/ashtuchkin/iconv-lite/wiki/Supported-Encodings).
Most singlebyte encodings are generated automatically from [node-iconv](https://github.com/bnoordhuis/node-iconv). Thank you Ben Noordhuis and libiconv authors!
Multibyte encodings are generated from [Unicode.org mappings](http://www.unicode.org/Public/MAPPINGS/) and [WHATWG Encoding Standard mappings](http://encoding.spec.whatwg.org/). Thank you, respective authors!
## Encoding/decoding speed
Comparison with node-iconv module (1000x256kb, on MacBook Pro, Core i5/2.6 GHz, Node v0.12.0).
Note: your results may vary, so please always check on your hardware.
A callback might also be given as a `stripBOM` parameter - it'll be called if BOM character was actually found.
* If you want to detect UTF-8 BOM when decoding other encodings, use [node-autodetect-decoder-stream](https://github.com/danielgindi/node-autodetect-decoder-stream) module.
* Encoding: No BOM added, unless overridden by `addBOM: true` option.
## UTF-16 Encodings
This library supports UTF-16LE, UTF-16BE and UTF-16 encodings. First two are straightforward, but UTF-16 is trying to be
smart about endianness in the following ways:
* Decoding: uses BOM and 'spaces heuristic' to determine input endianness. Default is UTF-16LE, but can be
overridden with `defaultEncoding: 'utf-16be'` option. Strips BOM unless `stripBOM: false`.
* Encoding: uses UTF-16LE and writes BOM by default. Use `addBOM: false` to override.
## Other notes
When decoding, be sure to supply a Buffer to decode() method, otherwise [bad things usually happen](https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding).
Untranslatable characters are set to � or ?. No transliteration is currently supported.
Node versions 0.10.31 and 0.11.13 are buggy, don't use them (see #65, #77).
// Variations, in roughly number of defined chars:
// * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT
// * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/
// * Big5-2003 (Taiwan standard) almost superset of cp950.
// * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers.
// * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard.
// many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years.
// Plus, it has 4 combining sequences.
// Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299
// because big5-hkscs is the only encoding to include astral characters in non-algorithmic way.
// Implementations are not consistent within browsers; sometimes labeled as just big5.
// MS Internet Explorer switches from big5 to big5-hkscs when a patch applied.
// Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31
// In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s.
// Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt
console.error('Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding');
console.error("iconv-lite warning: javascript files use encoding different from utf-8. See https://github.com/ashtuchkin/iconv-lite/wiki/Javascript-source-file-encodings for more info.");
*[[`705673d`](http://github.com/koajs/bodyparser/commit/705673d634818727dbdb25ee999560970bd268a2)] - feat: support xml (#131) (TZ | 天猪 <<atian25@qq.com>>)
*[[`db193f5`](http://github.com/koajs/bodyparser/commit/db193f5d46860393521ad38f90a554968b2ba98a)] - chore:replace indexOf with includes (#90) (coderzzp <<coderzzp@gmail.com>>)
4.2.0 / 2017-03-21
==================
* feat: ctx.request.rawBody to get raw request body (#70)
4.1.0 / 2017-03-02
==================
* deps: upgrade co-body@5 (#64)
4.0.0 / 2017-02-27
==================
* refactor: use async function and support koa@2 (#62)
2.3.0 / 2016-11-14
==================
* feat: support dynamic disable body parser
2.2.0 / 2016-05-16
==================
* feat: support enableTypes and text (#44)
2.1.0 / 2016-05-10
==================
* deps: co-body@4
2.0.1 / 2015-08-12
==================
* chore: upgrade co-body@3.1.0
2.0.0 / 2015-05-07
==================
* deps: co-body@2, default to strict mode
1.6.0 / 2015-05-01
==================
* feat: support custom error handler
1.5.0 / 2015-04-04
==================
* Use an empty object instead of null, if no body is parsed
1.4.1 / 2015-03-10
==================
* bump co-body@1.1.0
1.4.0 / 2015-02-26
==================
* feat: custom json request detect
1.3.1 / 2015-01-27
==================
* fix: extend
1.3.0 / 2014-11-27
==================
* support extendTypes
* Merge pull request #8 from coderhaoxin/json-patch
A body parser for koa, based on [co-body](https://github.com/tj/co-body). support `json`, `form` and `text` type body.
> Notice: this module don't support parsing multipart format data, please use [co-busboy](https://github.com/cojs/busboy) to parse multipart format data.
// if nothing was parsed, body will be an empty object {}
ctx.body=ctx.request.body;
});
```
## Options
***enableTypes**: parser will only parse when request type hits enableTypes, support `json/form/text/xml`, default is `['json', 'form']`.
***encoding**: requested encoding. Default is `utf-8` by `co-body`.
***formLimit**: limit of the `urlencoded` body. If the body ends up being larger than this limit, a 413 error code is returned. Default is `56kb`.
***jsonLimit**: limit of the `json` body. Default is `1mb`.
***textLimit**: limit of the `text` body. Default is `1mb`.
***xmlLimit**: limit of the `xml` body. Default is `1mb`.
***strict**: when set to true, JSON parser will only accept arrays and objects. Default is `true`. See [strict mode](https://github.com/cojs/co-body#options) in `co-body`. In strict mode, `ctx.request.body` will always be an object(or array), this avoid lots of type judging. But text body will always return string type.
***detectJSON**: custom json request detect function. Default is `null`.
```js
app.use(bodyparser({
detectJSON:function(ctx){
return/\.json$/i.test(ctx.path);
}
}));
```
* **extendTypes**: support extend types:
```js
app.use(bodyparser({
extendTypes:{
json:['application/x-javascript']// will parse application/x-javascript type body as a JSON string
}
}));
```
* **onerror**: support custom error handle, if `koa-bodyparser` throw an error, you can customize the response like:
```js
app.use(bodyparser({
onerror:function(err,ctx){
ctx.throw('body parse error',422);
}
}));
```
* **disableBodyParser**: you can dynamic disable body parser by set `ctx.disableBodyParser=true`.
```js
app.use(async (ctx, next) => {
if (ctx.path === '/disable') ctx.disableBodyParser = true;
await next();
});
app.use(bodyparser());
```
## Raw Body
You can access raw request body by `ctx.request.rawBody` after `koa-bodyparser` when:
1. `koa-bodyparser` parsed the request body.
2. `ctx.request.rawBody` is not present before `koa-bodyparser`.
## Koa 1 Support
To use `koa-bodyparser` with koa@1, please use [bodyparser 2.x](https://github.com/koajs/bodyparser/tree/2.x).
A querystring parsing and stringifying library with some added security.
Lead Maintainer: [Jordan Harband](https://github.com/ljharb)
The **qs** module was originally created and maintained by [TJ Holowaychuk](https://github.com/visionmedia/node-querystring).
## Usage
```javascript
varqs=require('qs');
varassert=require('assert');
varobj=qs.parse('a=c');
assert.deepEqual(obj,{a:'c'});
varstr=qs.stringify(obj);
assert.equal(str,'a=c');
```
### Parsing Objects
[](#preventEval)
```javascript
qs.parse(string,[options]);
```
**qs** allows you to create nested objects within your query strings, by surrounding the name of sub-keys with square brackets `[]`.
For example, the string `'foo[bar]=baz'` converts to:
```javascript
assert.deepEqual(qs.parse('foo[bar]=baz'),{
foo:{
bar:'baz'
}
});
```
When using the `plainObjects` option the parsed value is returned as a null object, created via `Object.create(null)` and as such you should be aware that prototype methods will not exist on it and a user may set those names to whatever value they like:
By default parameters that would overwrite properties on the object prototype are ignored, if you wish to keep the data from those fields either use `plainObjects` as mentioned above, or set `allowPrototypes` to `true` which will allow user input to overwrite those properties. *WARNING* It is generally a bad idea to enable this option as it can cause problems when attempting to use the properties that have been overwritten. Always be careful with this option.
**qs** will also limit specifying indices in an array to a maximum index of `20`. Any array members with an index of greater than `20` will
instead be converted to an object with the index as the key. This is needed to handle cases when someone sent, for example, `a[999999999]` and it will take significant time to iterate over this huge array.
```javascript
varwithMaxIndex=qs.parse('a[100]=b');
assert.deepEqual(withMaxIndex,{a:{'100':'b'}});
```
This limit can be overridden by passing an `arrayLimit` option:
Examples beyond this point will be shown as though the output is not URI encoded for clarity. Please note that the return values in these cases *will* be URI encoded during real usage.
When arrays are stringified, by default they are given explicit indices:
```javascript
qs.stringify({a:['b','c','d']});
// 'a[0]=b&a[1]=c&a[2]=d'
```
You may override this by setting the `indices` option to `false`:
```javascript
qs.stringify({a:['b','c','d']},{indices:false});
// 'a=b&a=c&a=d'
```
You may use the `arrayFormat` option to specify the format of the output array:
RFC3986 used as default option and encodes ' ' to *%20* which is backward compatible.
In the same time, output can be stringified as per RFC1738 with ' ' equal to '+'.
```
assert.equal(qs.stringify({ a: 'b c' }), 'a=b%20c');
assert.equal(qs.stringify({ a: 'b c' }, { format : 'RFC3986' }), 'a=b%20c');
assert.equal(qs.stringify({ a: 'b c' }, { format : 'RFC1738' }), 'a=b+c');
```
## Security
Please email [@ljharb](https://github.com/ljharb) or see https://tidelift.com/security if you have a potential security vulnerability to report.
## qs for enterprise
Available as part of the Tidelift Subscription
The maintainers of qs and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-qs?utm_source=npm-qs&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
-[Variant 1: Drop support for Node.js ≤ 4.4.x and 5.0.0 — 5.9.x.](#variant-1)(*recommended*)
-[Variant 2: Use a polyfill](#variant-2)
-[Variant 3: manual detection, with safeguards](#variant-3)
### Finding problematic bits of code using grep
Just run `grep -nrE '[^a-zA-Z](Slow)?Buffer\s*\(' --exclude-dir node_modules`.
It will find all the potentially unsafe places in your own code (with some considerably unlikely
exceptions).
### Finding problematic bits of code using Node.js 8
If you’re using Node.js ≥ 8.0.0 (which is recommended), Node.js exposes multiple options that help with finding the relevant pieces of code:
-`--trace-warnings` will make Node.js show a stack trace for this warning and other warnings that are printed by Node.js.
-`--trace-deprecation` does the same thing, but only for deprecation warnings.
-`--pending-deprecation` will show more types of deprecation warnings. In particular, it will show the `Buffer()` deprecation warning, even on Node.js 8.
You can set these flags using an environment variable:
(node:7147) [DEP0005] DeprecationWarning: The Buffer() and new Buffer() constructors are not recommended for use due to security and usability concerns. Please use the new Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() construction methods instead.
at showFlaggedDeprecation (buffer.js:127:13)
at new Buffer (buffer.js:148:3)
at Object.<anonymous>(/path/to/example.js:2:13)
[... more stack trace lines ...]
```
### Finding problematic bits of code using linters
also find calls to deprecated `Buffer()` API. Those rules are included in some pre-sets.
There is a drawback, though, that it doesn't always
[work correctly](https://github.com/chalker/safer-buffer#why-not-safe-buffer) when `Buffer` is
overriden e.g. with a polyfill, so recommended is a combination of this and some other method
described above.
<aid="variant-1"></a>
## Variant 1: Drop support for Node.js ≤ 4.4.x and 5.0.0 — 5.9.x.
This is the recommended solution nowadays that would imply only minimal overhead.
The Node.js 5.x release line has been unsupported since July 2016, and the Node.js 4.x release line reaches its End of Life in April 2018 (→ [Schedule](https://github.com/nodejs/Release#release-schedule)). This means that these versions of Node.js will *not* receive any updates, even in case of security issues, so using these release lines should be avoided, if at all possible.
What you would do in this case is to convert all `new Buffer()` or `Buffer()` calls to use `Buffer.alloc()` or `Buffer.from()`, in the following way:
- For `new Buffer(number)`, replace it with `Buffer.alloc(number)`.
- For `new Buffer(string)` (or `new Buffer(string, encoding)`), replace it with `Buffer.from(string)` (or `Buffer.from(string, encoding)`).
- For all other combinations of arguments (these are much rarer), also replace `new Buffer(...arguments)` with `Buffer.from(...arguments)`.
Note that `Buffer.alloc()` is also _faster_ on the current Node.js versions than
`new Buffer(size).fill(0)`, which is what you would otherwise need to ensure zero-filling.
standard: Use JavaScript Standard Style (https://standardjs.com)
/home/chalker/repo/safer-buffer/example.unsafe.js:2:13: 'Buffer()' was deprecated since v6. Use 'Buffer.alloc()' or 'Buffer.from()' (use 'https://www.npmjs.com/package/safe-buffer' for '<4.5.0') instead.
```
This is allocates and writes to console an uninitialized chunk of memory.
[standard](https://www.npmjs.com/package/standard) linter (among others) catch that and warn people