CoolFace
Apppublic

AK-21/Graphite-Industrial-Intelligence

sourceHugging Faceupdated 3mo agoView on Hugging Face
0likes
README.md318 linesDownload Raw Back to send
1# send2 3[![NPM Version][npm-version-image]][npm-url]4[![NPM Downloads][npm-downloads-image]][npm-url]5[![CI][github-actions-ci-image]][github-actions-ci-url]6[![Test Coverage][coveralls-image]][coveralls-url]7 8Send is a library for streaming files from the file system as a http response9supporting partial responses (Ranges), conditional-GET negotiation (If-Match,10If-Unmodified-Since, If-None-Match, If-Modified-Since), high test coverage,11and granular events which may be leveraged to take appropriate actions in your12application or framework.13 14Looking to serve up entire folders mapped to URLs? Try [serve-static](https://www.npmjs.org/package/serve-static).15 16## Installation17 18This is a [Node.js](https://nodejs.org/en/) module available through the19[npm registry](https://www.npmjs.com/). Installation is done using the20[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):21 22```bash23$ npm install send24```25 26## API27 28```js29var send = require('send')30```31 32### send(req, path, [options])33 34Create a new `SendStream` for the given path to send to a `res`. The `req` is35the Node.js HTTP request and the `path` is a urlencoded path to send (urlencoded,36not the actual file-system path).37 38#### Options39 40##### acceptRanges41 42Enable or disable accepting ranged requests, defaults to true.43Disabling this will not send `Accept-Ranges` and ignore the contents44of the `Range` request header.45 46##### cacheControl47 48Enable or disable setting `Cache-Control` response header, defaults to49true. Disabling this will ignore the `immutable` and `maxAge` options.50 51##### dotfiles52 53Set how "dotfiles" are treated when encountered. A dotfile is a file54or directory that begins with a dot ("."). Note this check is done on55the path itself without checking if the path actually exists on the56disk. If `root` is specified, only the dotfiles above the root are57checked (i.e. the root itself can be within a dotfile when set58to "deny").59 60  - `'allow'` No special treatment for dotfiles.61  - `'deny'` Send a 403 for any request for a dotfile.62  - `'ignore'` Pretend like the dotfile does not exist and 404.63 64The default value is _similar_ to `'ignore'`, with the exception that65this default will not ignore the files within a directory that begins66with a dot, for backward-compatibility.67 68##### end69 70Byte offset at which the stream ends, defaults to the length of the file71minus 1. The end is inclusive in the stream, meaning `end: 3` will include72the 4th byte in the stream.73 74##### etag75 76Enable or disable etag generation, defaults to true.77 78##### extensions79 80If a given file doesn't exist, try appending one of the given extensions,81in the given order. By default, this is disabled (set to `false`). An82example value that will serve extension-less HTML files: `['html', 'htm']`.83This is skipped if the requested file already has an extension.84 85##### immutable86 87Enable or disable the `immutable` directive in the `Cache-Control` response88header, defaults to `false`. If set to `true`, the `maxAge` option should89also be specified to enable caching. The `immutable` directive will prevent90supported clients from making conditional requests during the life of the91`maxAge` option to check if the file has changed.92 93##### index94 95By default send supports "index.html" files, to disable this96set `false` or to supply a new index pass a string or an array97in preferred order.98 99##### lastModified100 101Enable or disable `Last-Modified` header, defaults to true. Uses the file102system's last modified value.103 104##### maxAge105 106Provide a max-age in milliseconds for http caching, defaults to 0.107This can also be a string accepted by the108[ms](https://www.npmjs.org/package/ms#readme) module.109 110##### root111 112Serve files relative to `path`.113 114##### start115 116Byte offset at which the stream starts, defaults to 0. The start is inclusive,117meaning `start: 2` will include the 3rd byte in the stream.118 119#### Events120 121The `SendStream` is an event emitter and will emit the following events:122 123  - `error` an error occurred `(err)`124  - `directory` a directory was requested `(res, path)`125  - `file` a file was requested `(path, stat)`126  - `headers` the headers are about to be set on a file `(res, path, stat)`127  - `stream` file streaming has started `(stream)`128  - `end` streaming has completed129 130#### .pipe131 132The `pipe` method is used to pipe the response into the Node.js HTTP response133object, typically `send(req, path, options).pipe(res)`.134 135## Error-handling136 137By default when no `error` listeners are present an automatic response will be138made, otherwise you have full control over the response, aka you may show a 5xx139page etc.140 141## Caching142 143It does _not_ perform internal caching, you should use a reverse proxy cache144such as Varnish for this, or those fancy things called CDNs. If your145application is small enough that it would benefit from single-node memory146caching, it's small enough that it does not need caching at all ;).147 148## Debugging149 150To enable `debug()` instrumentation output export __DEBUG__:151 152```153$ DEBUG=send node app154```155 156## Running tests157 158```159$ npm install160$ npm test161```162 163## Examples164 165### Serve a specific file166 167This simple example will send a specific file to all requests.168 169```js170var http = require('http')171var send = require('send')172 173var server = http.createServer(function onRequest (req, res) {174  send(req, '/path/to/index.html')175    .pipe(res)176})177 178server.listen(3000)179```180 181### Serve all files from a directory182 183This simple example will just serve up all the files in a184given directory as the top-level. For example, a request185`GET /foo.txt` will send back `/www/public/foo.txt`.186 187```js188var http = require('http')189var parseUrl = require('parseurl')190var send = require('send')191 192var server = http.createServer(function onRequest (req, res) {193  send(req, parseUrl(req).pathname, { root: '/www/public' })194    .pipe(res)195})196 197server.listen(3000)198```199 200### Custom file types201 202```js203var extname = require('path').extname204var http = require('http')205var parseUrl = require('parseurl')206var send = require('send')207 208var server = http.createServer(function onRequest (req, res) {209  send(req, parseUrl(req).pathname, { root: '/www/public' })210    .on('headers', function (res, path) {211      switch (extname(path)) {212        case '.x-mt':213        case '.x-mtt':214          // custom type for these extensions215          res.setHeader('Content-Type', 'application/x-my-type')216          break217      }218    })219    .pipe(res)220})221 222server.listen(3000)223```224 225### Custom directory index view226 227This is an example of serving up a structure of directories with a228custom function to render a listing of a directory.229 230```js231var http = require('http')232var fs = require('fs')233var parseUrl = require('parseurl')234var send = require('send')235 236// Transfer arbitrary files from within /www/example.com/public/*237// with a custom handler for directory listing238var server = http.createServer(function onRequest (req, res) {239  send(req, parseUrl(req).pathname, { index: false, root: '/www/public' })240    .once('directory', directory)241    .pipe(res)242})243 244server.listen(3000)245 246// Custom directory handler247function directory (res, path) {248  var stream = this249 250  // redirect to trailing slash for consistent url251  if (!stream.hasTrailingSlash()) {252    return stream.redirect(path)253  }254 255  // get directory list256  fs.readdir(path, function onReaddir (err, list) {257    if (err) return stream.error(err)258 259    // render an index for the directory260    res.setHeader('Content-Type', 'text/plain; charset=UTF-8')261    res.end(list.join('\n') + '\n')262  })263}264```265 266### Serving from a root directory with custom error-handling267 268```js269var http = require('http')270var parseUrl = require('parseurl')271var send = require('send')272 273var server = http.createServer(function onRequest (req, res) {274  // your custom error-handling logic:275  function error (err) {276    res.statusCode = err.status || 500277    res.end(err.message)278  }279 280  // your custom headers281  function headers (res, path, stat) {282    // serve all files for download283    res.setHeader('Content-Disposition', 'attachment')284  }285 286  // your custom directory handling logic:287  function redirect () {288    res.statusCode = 301289    res.setHeader('Location', req.url + '/')290    res.end('Redirecting to ' + req.url + '/')291  }292 293  // transfer arbitrary files from within294  // /www/example.com/public/*295  send(req, parseUrl(req).pathname, { root: '/www/public' })296    .on('error', error)297    .on('directory', redirect)298    .on('headers', headers)299    .pipe(res)300})301 302server.listen(3000)303```304 305## License306 307[MIT](LICENSE)308 309[coveralls-image]: https://badgen.net/coveralls/c/github/pillarjs/send/master310[coveralls-url]: https://coveralls.io/r/pillarjs/send?branch=master311[github-actions-ci-image]: https://badgen.net/github/checks/pillarjs/send/master?label=linux312[github-actions-ci-url]: https://github.com/pillarjs/send/actions/workflows/ci.yml313[node-image]: https://badgen.net/npm/node/send314[node-url]: https://nodejs.org/en/download/315[npm-downloads-image]: https://badgen.net/npm/dm/send316[npm-url]: https://npmjs.org/package/send317[npm-version-image]: https://badgen.net/npm/v/send318