Projekt

Obecné

Profil

Stáhnout (6.19 KB) Statistiky
| Větev: | Revize:
1
# raw-body
2

    
3
[![NPM Version][npm-image]][npm-url]
4
[![NPM Downloads][downloads-image]][downloads-url]
5
[![Node.js Version][node-version-image]][node-version-url]
6
[![Build status][travis-image]][travis-url]
7
[![Test coverage][coveralls-image]][coveralls-url]
8

    
9
Gets the entire buffer of a stream either as a `Buffer` or a string.
10
Validates the stream's length against an expected length and maximum limit.
11
Ideal for parsing request bodies.
12

    
13
## Install
14

    
15
This is a [Node.js](https://nodejs.org/en/) module available through the
16
[npm registry](https://www.npmjs.com/). Installation is done using the
17
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
18

    
19
```sh
20
$ npm install raw-body
21
```
22

    
23
### TypeScript
24

    
25
This module includes a [TypeScript](https://www.typescriptlang.org/)
26
declaration file to enable auto complete in compatible editors and type
27
information for TypeScript projects. This module depends on the Node.js
28
types, so install `@types/node`:
29

    
30
```sh
31
$ npm install @types/node
32
```
33

    
34
## API
35

    
36
<!-- eslint-disable no-unused-vars -->
37

    
38
```js
39
var getRawBody = require('raw-body')
40
```
41

    
42
### getRawBody(stream, [options], [callback])
43

    
44
**Returns a promise if no callback specified and global `Promise` exists.**
45

    
46
Options:
47

    
48
- `length` - The length of the stream.
49
  If the contents of the stream do not add up to this length,
50
  an `400` error code is returned.
51
- `limit` - The byte limit of the body.
52
  This is the number of bytes or any string format supported by
53
  [bytes](https://www.npmjs.com/package/bytes),
54
  for example `1000`, `'500kb'` or `'3mb'`.
55
  If the body ends up being larger than this limit,
56
  a `413` error code is returned.
57
- `encoding` - The encoding to use to decode the body into a string.
58
  By default, a `Buffer` instance will be returned when no encoding is specified.
59
  Most likely, you want `utf-8`, so setting `encoding` to `true` will decode as `utf-8`.
60
  You can use any type of encoding supported by [iconv-lite](https://www.npmjs.org/package/iconv-lite#readme).
61

    
62
You can also pass a string in place of options to just specify the encoding.
63

    
64
If an error occurs, the stream will be paused, everything unpiped,
65
and you are responsible for correctly disposing the stream.
66
For HTTP requests, no handling is required if you send a response.
67
For streams that use file descriptors, you should `stream.destroy()` or `stream.close()` to prevent leaks.
68

    
69
## Errors
70

    
71
This module creates errors depending on the error condition during reading.
72
The error may be an error from the underlying Node.js implementation, but is
73
otherwise an error created by this module, which has the following attributes:
74

    
75
  * `limit` - the limit in bytes
76
  * `length` and `expected` - the expected length of the stream
77
  * `received` - the received bytes
78
  * `encoding` - the invalid encoding
79
  * `status` and `statusCode` - the corresponding status code for the error
80
  * `type` - the error type
81

    
82
### Types
83

    
84
The errors from this module have a `type` property which allows for the progamatic
85
determination of the type of error returned.
86

    
87
#### encoding.unsupported
88

    
89
This error will occur when the `encoding` option is specified, but the value does
90
not map to an encoding supported by the [iconv-lite](https://www.npmjs.org/package/iconv-lite#readme)
91
module.
92

    
93
#### entity.too.large
94

    
95
This error will occur when the `limit` option is specified, but the stream has
96
an entity that is larger.
97

    
98
#### request.aborted
99

    
100
This error will occur when the request stream is aborted by the client before
101
reading the body has finished.
102

    
103
#### request.size.invalid
104

    
105
This error will occur when the `length` option is specified, but the stream has
106
emitted more bytes.
107

    
108
#### stream.encoding.set
109

    
110
This error will occur when the given stream has an encoding set on it, making it
111
a decoded stream. The stream should not have an encoding set and is expected to
112
emit `Buffer` objects.
113

    
114
## Examples
115

    
116
### Simple Express example
117

    
118
```js
119
var contentType = require('content-type')
120
var express = require('express')
121
var getRawBody = require('raw-body')
122

    
123
var app = express()
124

    
125
app.use(function (req, res, next) {
126
  getRawBody(req, {
127
    length: req.headers['content-length'],
128
    limit: '1mb',
129
    encoding: contentType.parse(req).parameters.charset
130
  }, function (err, string) {
131
    if (err) return next(err)
132
    req.text = string
133
    next()
134
  })
135
})
136

    
137
// now access req.text
138
```
139

    
140
### Simple Koa example
141

    
142
```js
143
var contentType = require('content-type')
144
var getRawBody = require('raw-body')
145
var koa = require('koa')
146

    
147
var app = koa()
148

    
149
app.use(function * (next) {
150
  this.text = yield getRawBody(this.req, {
151
    length: this.req.headers['content-length'],
152
    limit: '1mb',
153
    encoding: contentType.parse(this.req).parameters.charset
154
  })
155
  yield next
156
})
157

    
158
// now access this.text
159
```
160

    
161
### Using as a promise
162

    
163
To use this library as a promise, simply omit the `callback` and a promise is
164
returned, provided that a global `Promise` is defined.
165

    
166
```js
167
var getRawBody = require('raw-body')
168
var http = require('http')
169

    
170
var server = http.createServer(function (req, res) {
171
  getRawBody(req)
172
    .then(function (buf) {
173
      res.statusCode = 200
174
      res.end(buf.length + ' bytes submitted')
175
    })
176
    .catch(function (err) {
177
      res.statusCode = 500
178
      res.end(err.message)
179
    })
180
})
181

    
182
server.listen(3000)
183
```
184

    
185
### Using with TypeScript
186

    
187
```ts
188
import * as getRawBody from 'raw-body';
189
import * as http from 'http';
190

    
191
const server = http.createServer((req, res) => {
192
  getRawBody(req)
193
  .then((buf) => {
194
    res.statusCode = 200;
195
    res.end(buf.length + ' bytes submitted');
196
  })
197
  .catch((err) => {
198
    res.statusCode = err.statusCode;
199
    res.end(err.message);
200
  });
201
});
202

    
203
server.listen(3000);
204
```
205

    
206
## License
207

    
208
[MIT](LICENSE)
209

    
210
[npm-image]: https://img.shields.io/npm/v/raw-body.svg
211
[npm-url]: https://npmjs.org/package/raw-body
212
[node-version-image]: https://img.shields.io/node/v/raw-body.svg
213
[node-version-url]: https://nodejs.org/en/download/
214
[travis-image]: https://img.shields.io/travis/stream-utils/raw-body/master.svg
215
[travis-url]: https://travis-ci.org/stream-utils/raw-body
216
[coveralls-image]: https://img.shields.io/coveralls/stream-utils/raw-body/master.svg
217
[coveralls-url]: https://coveralls.io/r/stream-utils/raw-body?branch=master
218
[downloads-image]: https://img.shields.io/npm/dm/raw-body.svg
219
[downloads-url]: https://npmjs.org/package/raw-body
(3-3/6)