express.static与res.sendFile

有什么区别,应该使用哪一个? 我的目标是简单地提供静态html页面和文件。

router.use('/', express.static(path.resolve(public + '/index.html'))) 

要么

 router.get('/', function(req, res) { res.sendFile(path.resolve(public + '/index.html')) }) 

静态中间件和sendFile()大部分是相同的 – 它们都将文件stream传递给响应stream。

不同之处在于express.static会:

  • 为你设置ETag
  • 允许你设置扩展回退(例如html – > htm)

sendFile另一方面会:

  • 根据文件扩展名设置Content-Type响应HTTP头

他们都会:

  • 在Cache-Control上设置max-age属性
  • 设置Last-Modified标题
  • 允许您通过选项对象设置任何其他标题
  • 允许您忽略dotfiles

使用静态中间件的主要优点是不需要为每个文件单独编写特定的path(或者清理参数),而只需将中间件指向正确的目录即可。

如果您想要从public目录中提供任何文件,则应该使用express.static中间件来提供挂载到您的应用程序根目录整个目录

(另外,您可能希望考虑将静态服务中间件作为项目的依赖项,作为serve-static ,以便可以独立于Express进行更新。)

 var serveStatic = require('serve-static'); // same as express.static /* ... app initialization stuff goes here ... */ router.use(serveStatic(public)); // assuming you've defined `public` to some path above 

这将通过发送文件来响应对文件的请求,读取用于响应目录根目录请求的index.html文件。

但是,如果你的路线中有某种复杂的逻辑(或者将来可能会出现这种情况), 那么你应该使用sendFile 。 例如,对于每分钟发送一个不同的favicon的服务器:

 router.get('/favicon.ico', function(req, res) { return res.sendFile(path.resolve(public, '/icons/' + new Date().getMinutes() + '.ico')); })