Serve a specific file
A route needs to return one known HTML, image, PDF, or other filesystem file.
Express.js · Module
res.sendFile() transfers a file from the server filesystem to the client. It accepts a path, optional serving options, and an optional callback for completion or errors.
Use res.sendFile() to transfer one file to the client. Supply an absolute path, or provide root so the path can be relative; options configure file-serving behavior, and an optional callback handles completion or errors.
res.sendFile(path, [options], [fn])| Name | Type | Description |
|---|---|---|
path | String | Path to the file to transfer; it must be absolute unless options.root is set. |
options | Object | undefined | Optional file-serving settings, including maxAge, root, lastModified, and headers. |
fn | Function | Optional callback invoked after completion or on error; receives err. |
The documentation describes the transfer and callback behavior but does not specify a separate return value.
import express from "express";
import path from "node:path";
const app = express();
const publicDir = path.join(process.cwd(), "public");
app.get("/files/:name", (req, res, next) => {
res.sendFile(req.params.name, { root: publicDir }, (err) => {
if (err) next(err);
});
});
app.listen(3000);Serves the requested file relative to a fixed directory and forwards transfer errors to Express.
A route needs to return one known HTML, image, PDF, or other filesystem file.
A request selects a filename within a controlled directory.
A response needs custom caching or HTTP headers for one file.
It transfers the file at the supplied path and sets Content-Type from the filename extension. The path must be absolute unless options.root is supplied.
Follow-up: How would you safely serve a user-selected file? Use a fixed absolute root and pass a relative name, then handle callback errors with next(err).
The options object configures serving, including maxAge, root, lastModified, and headers. maxAge defaults to 0, while lastModified defaults to true.
Follow-up: What cache-related behavior can be changed? Set maxAge for Cache-Control max-age and set lastModified to false to suppress Last-Modified.
The optional fn(err) callback runs after transfer completion or when an error occurs. If an error occurs while using it, the callback must finish the response or delegate to the next route.
Follow-up: What should a typical Express handler do on failure? Call next(err), unless it deliberately sends or ends an error response.
res.download()res.send()express.static()res.render()