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'))
})
Express' sendFile() function lets you send a raw file as a response to an HTTP request. You can think of res. sendFile() as Express' static middleware for a single endpoint.
You need express. static so your server can serve files that aren't being generated on the fly. It handles all the file loading and prevents path traversal attacks.
Express looks up the files relative to the static directory, so the name of the static directory is not part of the URL. To use multiple static assets directories, call the express.static middleware function multiple times: app. use(express. static('public')) app.
res. sendFile() is asynchronous and it will end its own response if it is successful. So, when you call res.
Static middleware and sendFile() are mostly the same - they both pipe the file stream to response stream.
The difference is that express.static will:
sendFile on the other hand will:
They both will:
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.
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'));
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With