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.

257 lines
7.6 KiB

3 months ago
  1. # serve-static
  2. [![NPM Version][npm-version-image]][npm-url]
  3. [![NPM Downloads][npm-downloads-image]][npm-url]
  4. [![Linux Build][github-actions-ci-image]][github-actions-ci-url]
  5. [![Windows Build][appveyor-image]][appveyor-url]
  6. [![Test Coverage][coveralls-image]][coveralls-url]
  7. ## Install
  8. This is a [Node.js](https://nodejs.org/en/) module available through the
  9. [npm registry](https://www.npmjs.com/). Installation is done using the
  10. [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
  11. ```sh
  12. $ npm install serve-static
  13. ```
  14. ## API
  15. ```js
  16. var serveStatic = require('serve-static')
  17. ```
  18. ### serveStatic(root, options)
  19. Create a new middleware function to serve files from within a given root
  20. directory. The file to serve will be determined by combining `req.url`
  21. with the provided root directory. When a file is not found, instead of
  22. sending a 404 response, this module will instead call `next()` to move on
  23. to the next middleware, allowing for stacking and fall-backs.
  24. #### Options
  25. ##### acceptRanges
  26. Enable or disable accepting ranged requests, defaults to true.
  27. Disabling this will not send `Accept-Ranges` and ignore the contents
  28. of the `Range` request header.
  29. ##### cacheControl
  30. Enable or disable setting `Cache-Control` response header, defaults to
  31. true. Disabling this will ignore the `immutable` and `maxAge` options.
  32. ##### dotfiles
  33. Set how "dotfiles" are treated when encountered. A dotfile is a file
  34. or directory that begins with a dot ("."). Note this check is done on
  35. the path itself without checking if the path actually exists on the
  36. disk. If `root` is specified, only the dotfiles above the root are
  37. checked (i.e. the root itself can be within a dotfile when set
  38. to "deny").
  39. - `'allow'` No special treatment for dotfiles.
  40. - `'deny'` Deny a request for a dotfile and 403/`next()`.
  41. - `'ignore'` Pretend like the dotfile does not exist and 404/`next()`.
  42. The default value is similar to `'ignore'`, with the exception that this
  43. default will not ignore the files within a directory that begins with a dot.
  44. ##### etag
  45. Enable or disable etag generation, defaults to true.
  46. ##### extensions
  47. Set file extension fallbacks. When set, if a file is not found, the given
  48. extensions will be added to the file name and search for. The first that
  49. exists will be served. Example: `['html', 'htm']`.
  50. The default value is `false`.
  51. ##### fallthrough
  52. Set the middleware to have client errors fall-through as just unhandled
  53. requests, otherwise forward a client error. The difference is that client
  54. errors like a bad request or a request to a non-existent file will cause
  55. this middleware to simply `next()` to your next middleware when this value
  56. is `true`. When this value is `false`, these errors (even 404s), will invoke
  57. `next(err)`.
  58. Typically `true` is desired such that multiple physical directories can be
  59. mapped to the same web address or for routes to fill in non-existent files.
  60. The value `false` can be used if this middleware is mounted at a path that
  61. is designed to be strictly a single file system directory, which allows for
  62. short-circuiting 404s for less overhead. This middleware will also reply to
  63. all methods.
  64. The default value is `true`.
  65. ##### immutable
  66. Enable or disable the `immutable` directive in the `Cache-Control` response
  67. header, defaults to `false`. If set to `true`, the `maxAge` option should
  68. also be specified to enable caching. The `immutable` directive will prevent
  69. supported clients from making conditional requests during the life of the
  70. `maxAge` option to check if the file has changed.
  71. ##### index
  72. By default this module will send "index.html" files in response to a request
  73. on a directory. To disable this set `false` or to supply a new index pass a
  74. string or an array in preferred order.
  75. ##### lastModified
  76. Enable or disable `Last-Modified` header, defaults to true. Uses the file
  77. system's last modified value.
  78. ##### maxAge
  79. Provide a max-age in milliseconds for http caching, defaults to 0. This
  80. can also be a string accepted by the [ms](https://www.npmjs.org/package/ms#readme)
  81. module.
  82. ##### redirect
  83. Redirect to trailing "/" when the pathname is a dir. Defaults to `true`.
  84. ##### setHeaders
  85. Function to set custom headers on response. Alterations to the headers need to
  86. occur synchronously. The function is called as `fn(res, path, stat)`, where
  87. the arguments are:
  88. - `res` the response object
  89. - `path` the file path that is being sent
  90. - `stat` the stat object of the file that is being sent
  91. ## Examples
  92. ### Serve files with vanilla node.js http server
  93. ```js
  94. var finalhandler = require('finalhandler')
  95. var http = require('http')
  96. var serveStatic = require('serve-static')
  97. // Serve up public/ftp folder
  98. var serve = serveStatic('public/ftp', { index: ['index.html', 'index.htm'] })
  99. // Create server
  100. var server = http.createServer(function onRequest (req, res) {
  101. serve(req, res, finalhandler(req, res))
  102. })
  103. // Listen
  104. server.listen(3000)
  105. ```
  106. ### Serve all files as downloads
  107. ```js
  108. var contentDisposition = require('content-disposition')
  109. var finalhandler = require('finalhandler')
  110. var http = require('http')
  111. var serveStatic = require('serve-static')
  112. // Serve up public/ftp folder
  113. var serve = serveStatic('public/ftp', {
  114. index: false,
  115. setHeaders: setHeaders
  116. })
  117. // Set header to force download
  118. function setHeaders (res, path) {
  119. res.setHeader('Content-Disposition', contentDisposition(path))
  120. }
  121. // Create server
  122. var server = http.createServer(function onRequest (req, res) {
  123. serve(req, res, finalhandler(req, res))
  124. })
  125. // Listen
  126. server.listen(3000)
  127. ```
  128. ### Serving using express
  129. #### Simple
  130. This is a simple example of using Express.
  131. ```js
  132. var express = require('express')
  133. var serveStatic = require('serve-static')
  134. var app = express()
  135. app.use(serveStatic('public/ftp', { index: ['default.html', 'default.htm'] }))
  136. app.listen(3000)
  137. ```
  138. #### Multiple roots
  139. This example shows a simple way to search through multiple directories.
  140. Files are searched for in `public-optimized/` first, then `public/` second
  141. as a fallback.
  142. ```js
  143. var express = require('express')
  144. var path = require('path')
  145. var serveStatic = require('serve-static')
  146. var app = express()
  147. app.use(serveStatic(path.join(__dirname, 'public-optimized')))
  148. app.use(serveStatic(path.join(__dirname, 'public')))
  149. app.listen(3000)
  150. ```
  151. #### Different settings for paths
  152. This example shows how to set a different max age depending on the served
  153. file type. In this example, HTML files are not cached, while everything else
  154. is for 1 day.
  155. ```js
  156. var express = require('express')
  157. var path = require('path')
  158. var serveStatic = require('serve-static')
  159. var app = express()
  160. app.use(serveStatic(path.join(__dirname, 'public'), {
  161. maxAge: '1d',
  162. setHeaders: setCustomCacheControl
  163. }))
  164. app.listen(3000)
  165. function setCustomCacheControl (res, path) {
  166. if (serveStatic.mime.lookup(path) === 'text/html') {
  167. // Custom Cache-Control for HTML files
  168. res.setHeader('Cache-Control', 'public, max-age=0')
  169. }
  170. }
  171. ```
  172. ## License
  173. [MIT](LICENSE)
  174. [appveyor-image]: https://badgen.net/appveyor/ci/dougwilson/serve-static/master?label=windows
  175. [appveyor-url]: https://ci.appveyor.com/project/dougwilson/serve-static
  176. [coveralls-image]: https://badgen.net/coveralls/c/github/expressjs/serve-static/master
  177. [coveralls-url]: https://coveralls.io/r/expressjs/serve-static?branch=master
  178. [github-actions-ci-image]: https://badgen.net/github/checks/expressjs/serve-static/master?label=linux
  179. [github-actions-ci-url]: https://github.com/expressjs/serve-static/actions/workflows/ci.yml
  180. [node-image]: https://badgen.net/npm/node/serve-static
  181. [node-url]: https://nodejs.org/en/download/
  182. [npm-downloads-image]: https://badgen.net/npm/dm/serve-static
  183. [npm-url]: https://npmjs.org/package/serve-static
  184. [npm-version-image]: https://badgen.net/npm/v/serve-static