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.

223 lines
6.4 KiB

6 months ago
  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][github-actions-ci-image]][github-actions-ci-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. ```js
  27. var getRawBody = require('raw-body')
  28. ```
  29. ### getRawBody(stream, [options], [callback])
  30. **Returns a promise if no callback specified and global `Promise` exists.**
  31. Options:
  32. - `length` - The length of the stream.
  33. If the contents of the stream do not add up to this length,
  34. an `400` error code is returned.
  35. - `limit` - The byte limit of the body.
  36. This is the number of bytes or any string format supported by
  37. [bytes](https://www.npmjs.com/package/bytes),
  38. for example `1000`, `'500kb'` or `'3mb'`.
  39. If the body ends up being larger than this limit,
  40. a `413` error code is returned.
  41. - `encoding` - The encoding to use to decode the body into a string.
  42. By default, a `Buffer` instance will be returned when no encoding is specified.
  43. Most likely, you want `utf-8`, so setting `encoding` to `true` will decode as `utf-8`.
  44. You can use any type of encoding supported by [iconv-lite](https://www.npmjs.org/package/iconv-lite#readme).
  45. You can also pass a string in place of options to just specify the encoding.
  46. If an error occurs, the stream will be paused, everything unpiped,
  47. and you are responsible for correctly disposing the stream.
  48. For HTTP requests, you may need to finish consuming the stream if
  49. you want to keep the socket open for future requests. For streams
  50. that use file descriptors, you should `stream.destroy()` or
  51. `stream.close()` to prevent leaks.
  52. ## Errors
  53. This module creates errors depending on the error condition during reading.
  54. The error may be an error from the underlying Node.js implementation, but is
  55. otherwise an error created by this module, which has the following attributes:
  56. * `limit` - the limit in bytes
  57. * `length` and `expected` - the expected length of the stream
  58. * `received` - the received bytes
  59. * `encoding` - the invalid encoding
  60. * `status` and `statusCode` - the corresponding status code for the error
  61. * `type` - the error type
  62. ### Types
  63. The errors from this module have a `type` property which allows for the programmatic
  64. determination of the type of error returned.
  65. #### encoding.unsupported
  66. This error will occur when the `encoding` option is specified, but the value does
  67. not map to an encoding supported by the [iconv-lite](https://www.npmjs.org/package/iconv-lite#readme)
  68. module.
  69. #### entity.too.large
  70. This error will occur when the `limit` option is specified, but the stream has
  71. an entity that is larger.
  72. #### request.aborted
  73. This error will occur when the request stream is aborted by the client before
  74. reading the body has finished.
  75. #### request.size.invalid
  76. This error will occur when the `length` option is specified, but the stream has
  77. emitted more bytes.
  78. #### stream.encoding.set
  79. This error will occur when the given stream has an encoding set on it, making it
  80. a decoded stream. The stream should not have an encoding set and is expected to
  81. emit `Buffer` objects.
  82. #### stream.not.readable
  83. This error will occur when the given stream is not readable.
  84. ## Examples
  85. ### Simple Express example
  86. ```js
  87. var contentType = require('content-type')
  88. var express = require('express')
  89. var getRawBody = require('raw-body')
  90. var app = express()
  91. app.use(function (req, res, next) {
  92. getRawBody(req, {
  93. length: req.headers['content-length'],
  94. limit: '1mb',
  95. encoding: contentType.parse(req).parameters.charset
  96. }, function (err, string) {
  97. if (err) return next(err)
  98. req.text = string
  99. next()
  100. })
  101. })
  102. // now access req.text
  103. ```
  104. ### Simple Koa example
  105. ```js
  106. var contentType = require('content-type')
  107. var getRawBody = require('raw-body')
  108. var koa = require('koa')
  109. var app = koa()
  110. app.use(function * (next) {
  111. this.text = yield getRawBody(this.req, {
  112. length: this.req.headers['content-length'],
  113. limit: '1mb',
  114. encoding: contentType.parse(this.req).parameters.charset
  115. })
  116. yield next
  117. })
  118. // now access this.text
  119. ```
  120. ### Using as a promise
  121. To use this library as a promise, simply omit the `callback` and a promise is
  122. returned, provided that a global `Promise` is defined.
  123. ```js
  124. var getRawBody = require('raw-body')
  125. var http = require('http')
  126. var server = http.createServer(function (req, res) {
  127. getRawBody(req)
  128. .then(function (buf) {
  129. res.statusCode = 200
  130. res.end(buf.length + ' bytes submitted')
  131. })
  132. .catch(function (err) {
  133. res.statusCode = 500
  134. res.end(err.message)
  135. })
  136. })
  137. server.listen(3000)
  138. ```
  139. ### Using with TypeScript
  140. ```ts
  141. import * as getRawBody from 'raw-body';
  142. import * as http from 'http';
  143. const server = http.createServer((req, res) => {
  144. getRawBody(req)
  145. .then((buf) => {
  146. res.statusCode = 200;
  147. res.end(buf.length + ' bytes submitted');
  148. })
  149. .catch((err) => {
  150. res.statusCode = err.statusCode;
  151. res.end(err.message);
  152. });
  153. });
  154. server.listen(3000);
  155. ```
  156. ## License
  157. [MIT](LICENSE)
  158. [npm-image]: https://img.shields.io/npm/v/raw-body.svg
  159. [npm-url]: https://npmjs.org/package/raw-body
  160. [node-version-image]: https://img.shields.io/node/v/raw-body.svg
  161. [node-version-url]: https://nodejs.org/en/download/
  162. [coveralls-image]: https://img.shields.io/coveralls/stream-utils/raw-body/master.svg
  163. [coveralls-url]: https://coveralls.io/r/stream-utils/raw-body?branch=master
  164. [downloads-image]: https://img.shields.io/npm/dm/raw-body.svg
  165. [downloads-url]: https://npmjs.org/package/raw-body
  166. [github-actions-ci-image]: https://img.shields.io/github/actions/workflow/status/stream-utils/raw-body/ci.yml?branch=master&label=ci
  167. [github-actions-ci-url]: https://github.com/jshttp/stream-utils/raw-body?query=workflow%3Aci