Express res.sendFile() Method
What you’ll learn
- How to serve files with
res.sendFile(). - How to use safe path handling and root constraints.
- How to send file responses with options and custom headers.
- How to handle missing file errors cleanly.
Syntax
javascript
res.sendFile(path [, options] [, fn])1
Send a static file with absolute path
javascript
var path = require('path');
app.get('/manual', function (req, res) {
var filePath = path.join(__dirname, 'files', 'manual.pdf');
res.sendFile(filePath);
});2
Use root option for controlled file access
javascript
app.get('/images/:name', function (req, res) {
res.sendFile(req.params.name, {
root: __dirname + '/public/images',
maxAge: '1h'
});
});3
Handle file send errors with callback
javascript
app.get('/terms', function (req, res) {
res.sendFile(__dirname + '/files/terms.txt', function (err) {
if (err && !res.headersSent) return res.status(404).send('File not found');
});
});⚠️ Common pitfalls
- Do not pass unvalidated user-controlled paths directly.
- Prefer absolute paths or
rootoption to avoid traversal issues. - Check
res.headersSentbefore sending fallback errors in callbacks.
❓ FAQ
It transfers a file from the server filesystem to the client as the HTTP response body.
Yes, unless you use the root option. Using resolved absolute paths is safer and clearer.
res.sendFile() serves a file directly, while res.download() adds attachment behavior for download prompts.
Yes, provide a callback and handle missing files or permission issues there.
Never pass unvalidated user input directly; use trusted path joins and root constraints.
Did you know?
res.sendFile() sends files from disk and supports options like root, maxAge, and headers.
4 people found this page helpful
