UNPKG

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