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.

306 lines
8.7 KiB

  1. # send
  2. [![NPM Version][npm-image]][npm-url]
  3. [![NPM Downloads][downloads-image]][downloads-url]
  4. [![Linux Build][travis-image]][travis-url]
  5. [![Windows Build][appveyor-image]][appveyor-url]
  6. [![Test Coverage][coveralls-image]][coveralls-url]
  7. Send is a library for streaming files from the file system as a http response
  8. supporting partial responses (Ranges), conditional-GET negotiation (If-Match,
  9. If-Unmodified-Since, If-None-Match, If-Modified-Since), high test coverage,
  10. and granular events which may be leveraged to take appropriate actions in your
  11. application or framework.
  12. Looking to serve up entire folders mapped to URLs? Try [serve-static](https://www.npmjs.org/package/serve-static).
  13. ## Installation
  14. This is a [Node.js](https://nodejs.org/en/) module available through the
  15. [npm registry](https://www.npmjs.com/). Installation is done using the
  16. [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
  17. ```bash
  18. $ npm install send
  19. ```
  20. ## API
  21. <!-- eslint-disable no-unused-vars -->
  22. ```js
  23. var send = require('send')
  24. ```
  25. ### send(req, path, [options])
  26. Create a new `SendStream` for the given path to send to a `res`. The `req` is
  27. the Node.js HTTP request and the `path` is a urlencoded path to send (urlencoded,
  28. not the actual file-system path).
  29. #### Options
  30. ##### acceptRanges
  31. Enable or disable accepting ranged requests, defaults to true.
  32. Disabling this will not send `Accept-Ranges` and ignore the contents
  33. of the `Range` request header.
  34. ##### cacheControl
  35. Enable or disable setting `Cache-Control` response header, defaults to
  36. true. Disabling this will ignore the `immutable` and `maxAge` options.
  37. ##### dotfiles
  38. Set how "dotfiles" are treated when encountered. A dotfile is a file
  39. or directory that begins with a dot ("."). Note this check is done on
  40. the path itself without checking if the path actually exists on the
  41. disk. If `root` is specified, only the dotfiles above the root are
  42. checked (i.e. the root itself can be within a dotfile when when set
  43. to "deny").
  44. - `'allow'` No special treatment for dotfiles.
  45. - `'deny'` Send a 403 for any request for a dotfile.
  46. - `'ignore'` Pretend like the dotfile does not exist and 404.
  47. The default value is _similar_ to `'ignore'`, with the exception that
  48. this default will not ignore the files within a directory that begins
  49. with a dot, for backward-compatibility.
  50. ##### end
  51. Byte offset at which the stream ends, defaults to the length of the file
  52. minus 1. The end is inclusive in the stream, meaning `end: 3` will include
  53. the 4th byte in the stream.
  54. ##### etag
  55. Enable or disable etag generation, defaults to true.
  56. ##### extensions
  57. If a given file doesn't exist, try appending one of the given extensions,
  58. in the given order. By default, this is disabled (set to `false`). An
  59. example value that will serve extension-less HTML files: `['html', 'htm']`.
  60. This is skipped if the requested file already has an extension.
  61. ##### immutable
  62. Enable or diable the `immutable` directive in the `Cache-Control` response
  63. header, defaults to `false`. If set to `true`, the `maxAge` option should
  64. also be specified to enable caching. The `immutable` directive will prevent
  65. supported clients from making conditional requests during the life of the
  66. `maxAge` option to check if the file has changed.
  67. ##### index
  68. By default send supports "index.html" files, to disable this
  69. set `false` or to supply a new index pass a string or an array
  70. in preferred order.
  71. ##### lastModified
  72. Enable or disable `Last-Modified` header, defaults to true. Uses the file
  73. system's last modified value.
  74. ##### maxAge
  75. Provide a max-age in milliseconds for http caching, defaults to 0.
  76. This can also be a string accepted by the
  77. [ms](https://www.npmjs.org/package/ms#readme) module.
  78. ##### root
  79. Serve files relative to `path`.
  80. ##### start
  81. Byte offset at which the stream starts, defaults to 0. The start is inclusive,
  82. meaning `start: 2` will include the 3rd byte in the stream.
  83. #### Events
  84. The `SendStream` is an event emitter and will emit the following events:
  85. - `error` an error occurred `(err)`
  86. - `directory` a directory was requested `(res, path)`
  87. - `file` a file was requested `(path, stat)`
  88. - `headers` the headers are about to be set on a file `(res, path, stat)`
  89. - `stream` file streaming has started `(stream)`
  90. - `end` streaming has completed
  91. #### .pipe
  92. The `pipe` method is used to pipe the response into the Node.js HTTP response
  93. object, typically `send(req, path, options).pipe(res)`.
  94. ### .mime
  95. The `mime` export is the global instance of of the
  96. [`mime` npm module](https://www.npmjs.com/package/mime).
  97. This is used to configure the MIME types that are associated with file extensions
  98. as well as other options for how to resolve the MIME type of a file (like the
  99. default type to use for an unknown file extension).
  100. ## Error-handling
  101. By default when no `error` listeners are present an automatic response will be
  102. made, otherwise you have full control over the response, aka you may show a 5xx
  103. page etc.
  104. ## Caching
  105. It does _not_ perform internal caching, you should use a reverse proxy cache
  106. such as Varnish for this, or those fancy things called CDNs. If your
  107. application is small enough that it would benefit from single-node memory
  108. caching, it's small enough that it does not need caching at all ;).
  109. ## Debugging
  110. To enable `debug()` instrumentation output export __DEBUG__:
  111. ```
  112. $ DEBUG=send node app
  113. ```
  114. ## Running tests
  115. ```
  116. $ npm install
  117. $ npm test
  118. ```
  119. ## Examples
  120. ### Small example
  121. ```js
  122. var http = require('http')
  123. var parseUrl = require('parseurl')
  124. var send = require('send')
  125. var server = http.createServer(function onRequest (req, res) {
  126. send(req, parseUrl(req).pathname).pipe(res)
  127. })
  128. server.listen(3000)
  129. ```
  130. ### Custom file types
  131. ```js
  132. var http = require('http')
  133. var parseUrl = require('parseurl')
  134. var send = require('send')
  135. // Default unknown types to text/plain
  136. send.mime.default_type = 'text/plain'
  137. // Add a custom type
  138. send.mime.define({
  139. 'application/x-my-type': ['x-mt', 'x-mtt']
  140. })
  141. var server = http.createServer(function onRequest (req, res) {
  142. send(req, parseUrl(req).pathname).pipe(res)
  143. })
  144. server.listen(3000)
  145. ```
  146. ### Custom directory index view
  147. This is a example of serving up a structure of directories with a
  148. custom function to render a listing of a directory.
  149. ```js
  150. var http = require('http')
  151. var fs = require('fs')
  152. var parseUrl = require('parseurl')
  153. var send = require('send')
  154. // Transfer arbitrary files from within /www/example.com/public/*
  155. // with a custom handler for directory listing
  156. var server = http.createServer(function onRequest (req, res) {
  157. send(req, parseUrl(req).pathname, {index: false, root: '/www/example.com/public'})
  158. .once('directory', directory)
  159. .pipe(res)
  160. })
  161. server.listen(3000)
  162. // Custom directory handler
  163. function directory (res, path) {
  164. var stream = this
  165. // redirect to trailing slash for consistent url
  166. if (!stream.hasTrailingSlash()) {
  167. return stream.redirect(path)
  168. }
  169. // get directory list
  170. fs.readdir(path, function onReaddir (err, list) {
  171. if (err) return stream.error(err)
  172. // render an index for the directory
  173. res.setHeader('Content-Type', 'text/plain; charset=UTF-8')
  174. res.end(list.join('\n') + '\n')
  175. })
  176. }
  177. ```
  178. ### Serving from a root directory with custom error-handling
  179. ```js
  180. var http = require('http')
  181. var parseUrl = require('parseurl')
  182. var send = require('send')
  183. var server = http.createServer(function onRequest (req, res) {
  184. // your custom error-handling logic:
  185. function error (err) {
  186. res.statusCode = err.status || 500
  187. res.end(err.message)
  188. }
  189. // your custom headers
  190. function headers (res, path, stat) {
  191. // serve all files for download
  192. res.setHeader('Content-Disposition', 'attachment')
  193. }
  194. // your custom directory handling logic:
  195. function redirect () {
  196. res.statusCode = 301
  197. res.setHeader('Location', req.url + '/')
  198. res.end('Redirecting to ' + req.url + '/')
  199. }
  200. // transfer arbitrary files from within
  201. // /www/example.com/public/*
  202. send(req, parseUrl(req).pathname, {root: '/www/example.com/public'})
  203. .on('error', error)
  204. .on('directory', redirect)
  205. .on('headers', headers)
  206. .pipe(res)
  207. })
  208. server.listen(3000)
  209. ```
  210. ## License
  211. [MIT](LICENSE)
  212. [npm-image]: https://img.shields.io/npm/v/send.svg
  213. [npm-url]: https://npmjs.org/package/send
  214. [travis-image]: https://img.shields.io/travis/pillarjs/send/master.svg?label=linux
  215. [travis-url]: https://travis-ci.org/pillarjs/send
  216. [appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/send/master.svg?label=windows
  217. [appveyor-url]: https://ci.appveyor.com/project/dougwilson/send
  218. [coveralls-image]: https://img.shields.io/coveralls/pillarjs/send/master.svg
  219. [coveralls-url]: https://coveralls.io/r/pillarjs/send?branch=master
  220. [downloads-image]: https://img.shields.io/npm/dm/send.svg
  221. [downloads-url]: https://npmjs.org/package/send