🌐 Nodejs.cn

serve-static 中间件

安装

🌐 Install

这是一个可以通过npm注册表获取的Node.js模块。安装可以使用npm install命令完成:

🌐 This is a Node.js module available through the npm registry. Installation is done using the npm install command:

Terminal window
npm install serve-static

Note

serve-static 不包含其自身的 TypeScript 类型定义。如果你使用 TypeScript,还需要作为开发依赖从 DefinitelyTyped 安装社区维护的类型:

Terminal window
npm install --save-dev @types/serve-static

API

const serveStatic = require('serve-static');

serveStatic(root, options)

创建一个新的中间件函数,从给定的根目录中提供文件。要提供的文件将通过将 req.url 与提供的根目录结合来确定。当未找到文件时,该模块不会发送 404 响应,而是调用 next() 以继续下一个中间件,从而允许堆叠和备用方案。

🌐 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. 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.

选项

🌐 Options

acceptRanges

启用或禁用接受范围请求,默认值为 true。禁用此功能将不会发送 Accept-Ranges 并忽略 Range 请求头的内容。

🌐 Enable or disable accepting ranged requests, defaults to true. Disabling this will not send Accept-Ranges and ignore the contents of the Range request header.

cacheControl

启用或禁用设置 Cache-Control 响应头,默认值为 true。禁用此选项将忽略 immutablemaxAge 选项。

🌐 Enable or disable setting Cache-Control response header, defaults to true. Disabling this will ignore the immutable and maxAge options.

dotfiles

设置在遇到“点文件”(dotfiles)时的处理方式。点文件是以点(“.”)开头的文件或目录。请注意,此检查是在路径本身上进行的,而不检查路径是否实际存在于磁盘上。如果指定了 root,则只检查根目录上方的点文件(即当设置为“拒绝”时,根目录本身可以位于点文件中)。

🌐 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”).

  • 'allow' 对点文件没有特殊处理。
  • 'deny' 拒绝对点文件的请求并返回 403/next()
  • 'ignore' 假装该点文件不存在并返回 404/next()

默认值是 'ignore'

🌐 The default value is 'ignore'.

etag

启用或禁用 etag 生成,默认为 true。

🌐 Enable or disable etag generation, defaults to true.

extensions

设置文件扩展名回退。当设置后,如果未找到文件,将把给定的扩展名添加到文件名中并进行搜索。第一个存在的文件将被提供。例如:['html', 'htm']

🌐 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'].

默认值是 false

🌐 The default value is false.

fallthrough

将中间件设置为让客户端错误作为未处理请求传下去,否则转发客户端错误。区别在于,当这个值为 true 时,像错误请求或请求不存在的文件这样的客户端错误会导致该中间件简单地 next() 到你的下一个中间件。当这个值为 false 时,这些错误(即使是 404)也会触发 next(err)

🌐 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. When this value is false, these errors (even 404s), will invoke next(err).

通常希望 true 这样可以将多个物理目录映射到相同的网页地址,或者用于路由填充不存在的文件。

🌐 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.

如果将此中间件挂载在仅设计为单个文件系统目录的路径上,可以使用值 false,这允许通过短路 404 来减少开销。此中间件也会响应所有方法。

🌐 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. This middleware will also reply to all methods.

默认值是 true

🌐 The default value is true.

immutable

Cache-Control 响应头中启用或禁用 immutable 指令,默认为 false。如果设置为 true,还应指定 maxAge 选项以启用缓存。 immutable 指令将在 maxAge 选项的有效期内阻止支持的客户端发出条件请求以检查文件是否已更改。

🌐 Enable or disable the immutable directive in the Cache-Control response header, defaults to false. If set to true, the maxAge option should also be specified to enable caching. 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.

index

默认情况下,这个模块会在请求目录时发送“index.html”文件。要禁用此功能,请设置 false,或者要提供新的索引,可以传入一个字符串或按优先顺序的数组。

🌐 By default this module will send “index.html” files in response to a request on a directory. To disable this set false or to supply a new index pass a string or an array in preferred order.

lastModified

启用或禁用 Last-Modified 头,默认为 true。使用文件系统的最后修改时间值。

🌐 Enable or disable Last-Modified header, defaults to true. Uses the file system’s last modified value.

maxAge

为HTTP缓存提供一个以毫秒为单位的max-age,默认为0。这也可以是ms模块接受的字符串。

🌐 Provide a max-age in milliseconds for http caching, defaults to 0. This can also be a string accepted by the ms module.

redirect

当路径名是目录时,重定向到尾部的“/”。默认为 true

🌐 Redirect to trailing ”/” when the pathname is a dir. Defaults to true.

setHeaders

用于在响应上设置自定义头的函数。对头的修改需要同步进行。该函数被调用为 fn(res, path, stat),其参数如下:

🌐 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:

  • res 响应对象
  • path 被发送的文件路径
  • stat 正在发送文件的状态对象

例子

🌐 Examples

使用原生 node.js http 服务器提供文件

🌐 Serve files with vanilla node.js http server

const finalhandler = require('finalhandler');
const http = require('http');
const serveStatic = require('serve-static');
// Serve up public/ftp folder
const serve = serveStatic('public/ftp', { index: ['index.html', 'index.htm'] });
// Create server
const server = http.createServer((req, res) => {
serve(req, res, finalhandler(req, res));
});
// Listen
server.listen(3000);

将所有文件作为下载提供

🌐 Serve all files as downloads

const contentDisposition = require('content-disposition');
const finalhandler = require('finalhandler');
const http = require('http');
const serveStatic = require('serve-static');
// Serve up public/ftp folder
const 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
const server = http.createServer((req, res) => {
serve(req, res, finalhandler(req, res));
});
// Listen
server.listen(3000);

使用快捷方式提供服务

🌐 Serving using express

简单

🌐 Simple

这是一个使用 Express 的简单示例。

🌐 This is a simple example of using Express.

const express = require('express');
const serveStatic = require('serve-static');
const app = express();
app.use(serveStatic('public/ftp', { index: ['default.html', 'default.htm'] }));
app.listen(3000);

多重根

🌐 Multiple roots

这个例子展示了一种在多个目录中搜索的简单方法。文件首先在 public-optimized/ 中搜索,然后作为备用在 public/ 中搜索。

🌐 This example shows a simple way to search through multiple directories. Files are searched for in public-optimized/ first, then public/ second as a fallback.

const express = require('express');
const path = require('path');
const serveStatic = require('serve-static');
const app = express();
app.use(serveStatic(path.join(__dirname, 'public-optimized')));
app.use(serveStatic(path.join(__dirname, 'public')));
app.listen(3000);

路径的不同设置

🌐 Different settings for paths

此示例展示了如何根据提供的文件设置不同的最大年龄。在此示例中,HTML 文件不被缓存,而其他所有文件的缓存时间为 1 天。

🌐 This example shows how to set a different max age depending on the served file. In this example, HTML files are not cached, while everything else is for 1 day.

const express = require('express');
const path = require('path');
const serveStatic = require('serve-static');
const app = express();
app.use(
serveStatic(path.join(__dirname, 'public'), {
maxAge: '1d',
setHeaders: setCustomCacheControl,
})
);
app.listen(3000);
function setCustomCacheControl(res, file) {
if (path.extname(file) === '.html') {
// Custom Cache-Control for HTML files
res.setHeader('Cache-Control', 'public, max-age=0');
}
}

许可证

🌐 License

MIT