serve-static

NPM Version NPM Downloads Linux Build Windows Build Test Coverage

Install安装

This is a Node.js module available through the npm registry. 这是一个Node.js模块,可通过npm注册表获得。Installation is done using the npm install command:使用npm install命令完成安装:

$ npm install serve-static

API

var serveStatic = require('serve-static')

serveStatic(root, options)

Create a new middleware function to serve files from within a given root directory. 创建一个新的中间件函数,为给定根目录中的文件提供服务。The file to serve will be determined by combining req.url with the provided root directory. 将通过将req.url与提供的根目录相结合来确定要提供的文件。When a file is not found, instead of sending a 404 response, this module will instead call next() to move on to the next middleware, allowing for stacking and fall-backs.当找不到文件时,此模块将调用next(),而不是发送404响应,以转到下一个中间件,从而允许堆叠和回退。

Options

acceptRanges

Enable or disable accepting ranged requests, defaults to true. 启用或禁用接受范围请求,默认为trueDisabling this will not send Accept-Ranges and ignore the contents of the Range request header.禁用此选项将不会发送Accept-Ranges并忽略Range请求标头的内容。

cacheControl

Enable or disable setting Cache-Control response header, defaults to true. 启用或禁用设置Cache-Control响应标头,默认为trueDisabling this will ignore the immutable and maxAge options.禁用此选项将忽略immutablemaxAge选项。

dotfiles

Set how "dotfiles" are treated when encountered. 设置遇到“点文件”时如何处理。A dotfile is a file or directory that begins with a dot ("."). 点文件是以点(“.”)开头的文件或目录。Note this check is done on the path itself without checking if the path actually exists on the disk. 注意:此检查是在路径本身上进行的,而不检查磁盘上是否确实存在该路径。If root is specified, only the dotfiles above the root are checked (i.e. the root itself can be within a dotfile when set to "deny").如果指定了root,则仅检查根上的点文件(即,当设置为“拒绝”时,根本身可以位于点文件内)。

The default value is similar to 'ignore', with the exception that this default will not ignore the files within a directory that begins with a dot.默认值类似于'ignore',只是此默认值不会忽略以点开头的目录中的文件。

etag

Enable or disable etag generation, defaults to true.启用或禁用etag生成,默认为true

extensions扩展

Set file extension fallbacks. When set, if a file is not found, the given extensions will be added to the file name and search for. 设置文件扩展名回退。设置后,如果未找到文件,则会将给定的扩展名添加到文件名并搜索。The first that exists will be served. 存在的第一个将被提供。Example: ['html', 'htm'].示例:['html', 'htm']

The default value is false.默认值为false

fallthrough

Set the middleware to have client errors fall-through as just unhandled requests, otherwise forward a client error. 将中间件设置为将客户端错误作为未处理的请求处理,否则转发客户端错误。The difference is that client errors like a bad request or a request to a non-existent file will cause this middleware to simply next() to your next middleware when this value is true. 不同之处在于,客户机错误(如错误请求或对不存在的文件的请求)将导致此中间件在该值为true时直接转到next()到下一个中间件。When this value is false, these errors (even 404s), will invoke next(err).当该值为false时,这些错误(甚至404)将调用next(err)

Typically true is desired such that multiple physical directories can be mapped to the same web address or for routes to fill in non-existent files.通常需要true,以便多个物理目录可以映射到同一web地址,或者路由填充不存在的文件。

The value false can be used if this middleware is mounted at a path that is designed to be strictly a single file system directory, which allows for short-circuiting 404s for less overhead. 如果该中间件安装在严格设计为单个文件系统目录的路径上,则可以使用false值,该路径允许短路404以减少开销。This middleware will also reply to all methods.该中间件还将响应所有方法。

The default value is true.默认值为true

immutable

Enable or disable the immutable directive in the Cache-Control response header, defaults to false. Cache-Control响应头中启用或禁用immutable指令,默认为falseIf set to true, the maxAge option should also be specified to enable caching. 如果设置为true,还应指定maxAge选项以启用缓存。The immutable directive will prevent supported clients from making conditional requests during the life of the maxAge option to check if the file has changed.immutable指令将防止受支持的客户端在maxAge选项的生命周期内发出条件请求,以检查文件是否已更改。

index

By default this module will send "index.html" files in response to a request on a directory. 默认情况下,此模块将发送“index.html”文件以响应目录上的请求。To disable this set false or to supply a new index pass a string or an array in preferred order.若要禁用此设置false或提供新索引,请按首选顺序传递字符串或数组。

lastModified

Enable or disable Last-Modified header, defaults to true. 启用或禁用Last-Modified的标头,默认为trueUses the file system's last modified value.使用文件系统上次修改的值。

maxAge

Provide a max-age in milliseconds for http caching, defaults to 0. 提供http缓存的最大时间(以毫秒为单位),默认值为0。This can also be a string accepted by the ms module.这也可以是ms模块接受的字符串。

redirect

Redirect to trailing "/" when the pathname is a dir. 当路径名为目录时,重定向到尾部“/”。Defaults to true.默认为true

setHeaders

Function to set custom headers on response. 函数设置响应的自定义标题。Alterations to the headers need to occur synchronously. 对标题的更改需要同步进行。The function is called as fn(res, path, stat), where the arguments are:该函数以fn(res, path, stat)的形式调用,其中参数为:

Examples例子

Serve files with vanilla node.js http server使用vanilla node.js http服务器提供文件

var finalhandler = require('finalhandler')
var http = require('http')
var serveStatic = require('serve-static')

// Serve up public/ftp folder
var serve = serveStatic('public/ftp', { 'index': ['index.html', 'index.htm'] })

// Create server
var server = http.createServer(function onRequest (req, res) {
  serve(req, res, finalhandler(req, res))
})

// Listen
server.listen(3000)

Serve all files as downloads将所有文件作为下载提供

var contentDisposition = require('content-disposition')
var finalhandler = require('finalhandler')
var http = require('http')
var serveStatic = require('serve-static')

// Serve up public/ftp folder
var serve = serveStatic('public/ftp', {
  'index': false,
  'setHeaders': setHeaders
})

// Set header to force download
function setHeaders (res, path) {
  res.setHeader('Content-Disposition', contentDisposition(path))
}

// Create server
var server = http.createServer(function onRequest (req, res) {
  serve(req, res, finalhandler(req, res))
})

// Listen
server.listen(3000)

Serving using express供Express使用

Simple简单的

This is a simple example of using Express.这是一个使用Express的简单示例。

var express = require('express')
var serveStatic = require('serve-static')

var app = express()

app.use(serveStatic('public/ftp', { 'index': ['default.html', 'default.htm'] }))
app.listen(3000)

Multiple roots多根

This example shows a simple way to search through multiple directories. 此示例显示了一种在多个目录中搜索的简单方法。Files are look for in public-optimized/ first, then public/ second as a fallback.文件先在public-optimized/中查找,然后再在public/中查找作为回退。

var express = require('express')
var path = require('path')
var serveStatic = require('serve-static')

var app = express()

app.use(serveStatic(path.join(__dirname, 'public-optimized')))
app.use(serveStatic(path.join(__dirname, 'public')))
app.listen(3000)

Different settings for paths路径的不同设置

This example shows how to set a different max age depending on the served file type. 此示例显示如何根据所服务的文件类型设置不同的最大保存期。In this example, HTML files are not cached, while everything else is for 1 day.在本例中,HTML文件不会被缓存,而其他所有文件都会被缓存一天。

var express = require('express')
var path = require('path')
var serveStatic = require('serve-static')

var app = express()

app.use(serveStatic(path.join(__dirname, 'public'), {
  maxAge: '1d',
  setHeaders: setCustomCacheControl
}))

app.listen(3000)

function setCustomCacheControl (res, path) {
  if (serveStatic.mime.lookup(path) === 'text/html') {
    // Custom Cache-Control for HTML files
    res.setHeader('Cache-Control', 'public, max-age=0')
  }
}

License许可证

MIT