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'));
})