UNPKG

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