26

What's the difference and which should I use? My goal is to simply serve static html pages and files.

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

or

router.get('/', function(req, res) {
  res.sendFile(path.resolve(public + '/index.html'))
})
Mika
  • 1,112
  • 4
  • 15
  • 30
  • 2
    Are you asking, difference between `use` and `get`. `router.use` serves all the 4 http verbs, `get`, `post` bla bla. `router.get` only serves things if the verb is `get` – Swaraj Giri Jul 15 '15 at 08:35
  • `router.get('/', express.static(path.resolve(public + '/index.html')))` does not work. So router.get...sendFile.. is more proper way? Because it uses only get verb? – Mika Jul 15 '15 at 08:38
  • Possible duplicate: http://stackoverflow.com/questions/15601703/difference-between-app-use-and-app-get-in-express-js – Stephen Wright Jul 15 '15 at 08:38
  • 5
    @StephenWright This question is specifically about `sendFile` vs. `express.static`, not `use` vs. `get`. – Dan Nissenbaum Jun 03 '16 at 14:33

2 Answers2

22

Static middleware and sendFile() are mostly the same - they both pipe the file stream to response stream.

The difference is that express.static will:

  • set ETag for you
  • allow you to set extension fallbacks (for example html -> htm)

sendFile on the other hand will:

  • set the Content-Type response HTTP header based on file extension

They both will:

  • set max-age property on Cache-Control
  • set Last-Modified header
  • allow you to set any other headers through options object
  • allow you to ignore dotfiles

The main advantage of using static middleware is that you don't need to write specific route for every file separately (or sanitize parameters) but just point the middleware to the right directory.

kyrisu
  • 4,541
  • 10
  • 43
  • 66
5

If you want to serve any files from your public directory, you should use the express.static middleware to serve the entire directory, mounted to your app root.

(Also, you may wish to consider including the static serving middleware as a dependency of your project, as serve-static, so that it may update independently of 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

This will respond to requests for files by sending the files, reading index.html files for responding to requests for directory roots.

If, however, you have some kind of complex logic in your route (or you may at some point in the future), then you should use sendFile. For example, for a server that sends a different favicon every minute:

router.get('/favicon.ico', function(req, res) {
  return res.sendFile(path.resolve(public, '/icons/' + new Date().getMinutes() + '.ico'));
})
Stuart P. Bentley
  • 10,195
  • 10
  • 55
  • 84