Why use `express.static` instead of just `response.sendFile`?

Viewed 72

Simple question. In an Express app, when looking to serve files under a certain root directory, theres the express.static middleware like so:

app.use(base, express.static(root));

But it looks like the same thing can be done by just using response.sendFile like so:

app.use(base, (req, res) => res.sendFile(req.path, { root: root }));

What the advantage of one over the other, and when would I use each?

1 Answers

res.sendFile uses send package underly.

Send is a library for streaming files from the file system as a http response supporting partial responses (Ranges), conditional-GET negotiation (If-Match, If-Unmodified-Since, If-None-Match, If-Modified-Since), high test coverage, and granular events which may be leveraged to take appropriate actions in your application or framework.

Some files like user files may require the program to perform some logic to determine whether to send and the path of the file. So, it provides fine-grained support for serving files.

But for pure static files such as HTML, JS, CSS, we do not need fine-grain control, so we can use express.static

express.static is serve-static, it serve up entire folders mapped to URLs.

Related