You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

README.md 6.2KB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. # raw-body
  2. [![NPM Version][npm-image]][npm-url]
  3. [![NPM Downloads][downloads-image]][downloads-url]
  4. [![Node.js Version][node-version-image]][node-version-url]
  5. [![Build status][travis-image]][travis-url]
  6. [![Test coverage][coveralls-image]][coveralls-url]
  7. Gets the entire buffer of a stream either as a `Buffer` or a string.
  8. Validates the stream's length against an expected length and maximum limit.
  9. Ideal for parsing request bodies.
  10. ## Install
  11. This is a [Node.js](https://nodejs.org/en/) module available through the
  12. [npm registry](https://www.npmjs.com/). Installation is done using the
  13. [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
  14. ```sh
  15. $ npm install raw-body
  16. ```
  17. ### TypeScript
  18. This module includes a [TypeScript](https://www.typescriptlang.org/)
  19. declaration file to enable auto complete in compatible editors and type
  20. information for TypeScript projects. This module depends on the Node.js
  21. types, so install `@types/node`:
  22. ```sh
  23. $ npm install @types/node
  24. ```
  25. ## API
  26. <!-- eslint-disable no-unused-vars -->
  27. ```js
  28. var getRawBody = require('raw-body')
  29. ```
  30. ### getRawBody(stream, [options], [callback])
  31. **Returns a promise if no callback specified and global `Promise` exists.**
  32. Options:
  33. - `length` - The length of the stream.
  34. If the contents of the stream do not add up to this length,
  35. an `400` error code is returned.
  36. - `limit` - The byte limit of the body.
  37. This is the number of bytes or any string format supported by
  38. [bytes](https://www.npmjs.com/package/bytes),
  39. for example `1000`, `'500kb'` or `'3mb'`.
  40. If the body ends up being larger than this limit,
  41. a `413` error code is returned.
  42. - `encoding` - The encoding to use to decode the body into a string.
  43. By default, a `Buffer` instance will be returned when no encoding is specified.
  44. Most likely, you want `utf-8`, so setting `encoding` to `true` will decode as `utf-8`.
  45. You can use any type of encoding supported by [iconv-lite](https://www.npmjs.org/package/iconv-lite#readme).
  46. You can also pass a string in place of options to just specify the encoding.
  47. If an error occurs, the stream will be paused, everything unpiped,
  48. and you are responsible for correctly disposing the stream.
  49. For HTTP requests, no handling is required if you send a response.
  50. For streams that use file descriptors, you should `stream.destroy()` or `stream.close()` to prevent leaks.
  51. ## Errors
  52. This module creates errors depending on the error condition during reading.
  53. The error may be an error from the underlying Node.js implementation, but is
  54. otherwise an error created by this module, which has the following attributes:
  55. * `limit` - the limit in bytes
  56. * `length` and `expected` - the expected length of the stream
  57. * `received` - the received bytes
  58. * `encoding` - the invalid encoding
  59. * `status` and `statusCode` - the corresponding status code for the error
  60. * `type` - the error type
  61. ### Types
  62. The errors from this module have a `type` property which allows for the progamatic
  63. determination of the type of error returned.
  64. #### encoding.unsupported
  65. This error will occur when the `encoding` option is specified, but the value does
  66. not map to an encoding supported by the [iconv-lite](https://www.npmjs.org/package/iconv-lite#readme)
  67. module.
  68. #### entity.too.large
  69. This error will occur when the `limit` option is specified, but the stream has
  70. an entity that is larger.
  71. #### request.aborted
  72. This error will occur when the request stream is aborted by the client before
  73. reading the body has finished.
  74. #### request.size.invalid
  75. This error will occur when the `length` option is specified, but the stream has
  76. emitted more bytes.
  77. #### stream.encoding.set
  78. This error will occur when the given stream has an encoding set on it, making it
  79. a decoded stream. The stream should not have an encoding set and is expected to
  80. emit `Buffer` objects.
  81. ## Examples
  82. ### Simple Express example
  83. ```js
  84. var contentType = require('content-type')
  85. var express = require('express')
  86. var getRawBody = require('raw-body')
  87. var app = express()
  88. app.use(function (req, res, next) {
  89. getRawBody(req, {
  90. length: req.headers['content-length'],
  91. limit: '1mb',
  92. encoding: contentType.parse(req).parameters.charset
  93. }, function (err, string) {
  94. if (err) return next(err)
  95. req.text = string
  96. next()
  97. })
  98. })
  99. // now access req.text
  100. ```
  101. ### Simple Koa example
  102. ```js
  103. var contentType = require('content-type')
  104. var getRawBody = require('raw-body')
  105. var koa = require('koa')
  106. var app = koa()
  107. app.use(function * (next) {
  108. this.text = yield getRawBody(this.req, {
  109. length: this.req.headers['content-length'],
  110. limit: '1mb',
  111. encoding: contentType.parse(this.req).parameters.charset
  112. })
  113. yield next
  114. })
  115. // now access this.text
  116. ```
  117. ### Using as a promise
  118. To use this library as a promise, simply omit the `callback` and a promise is
  119. returned, provided that a global `Promise` is defined.
  120. ```js
  121. var getRawBody = require('raw-body')
  122. var http = require('http')
  123. var server = http.createServer(function (req, res) {
  124. getRawBody(req)
  125. .then(function (buf) {
  126. res.statusCode = 200
  127. res.end(buf.length + ' bytes submitted')
  128. })
  129. .catch(function (err) {
  130. res.statusCode = 500
  131. res.end(err.message)
  132. })
  133. })
  134. server.listen(3000)
  135. ```
  136. ### Using with TypeScript
  137. ```ts
  138. import * as getRawBody from 'raw-body';
  139. import * as http from 'http';
  140. const server = http.createServer((req, res) => {
  141. getRawBody(req)
  142. .then((buf) => {
  143. res.statusCode = 200;
  144. res.end(buf.length + ' bytes submitted');
  145. })
  146. .catch((err) => {
  147. res.statusCode = err.statusCode;
  148. res.end(err.message);
  149. });
  150. });
  151. server.listen(3000);
  152. ```
  153. ## License
  154. [MIT](LICENSE)
  155. [npm-image]: https://img.shields.io/npm/v/raw-body.svg
  156. [npm-url]: https://npmjs.org/package/raw-body
  157. [node-version-image]: https://img.shields.io/node/v/raw-body.svg
  158. [node-version-url]: https://nodejs.org/en/download/
  159. [travis-image]: https://img.shields.io/travis/stream-utils/raw-body/master.svg
  160. [travis-url]: https://travis-ci.org/stream-utils/raw-body
  161. [coveralls-image]: https://img.shields.io/coveralls/stream-utils/raw-body/master.svg
  162. [coveralls-url]: https://coveralls.io/r/stream-utils/raw-body?branch=master
  163. [downloads-image]: https://img.shields.io/npm/dm/raw-body.svg
  164. [downloads-url]: https://npmjs.org/package/raw-body