0
0
Expressframework~8 mins

res.download for file downloads in Express - Performance & Optimization

Choose your learning style9 modes available
Performance: res.download for file downloads
MEDIUM IMPACT
This affects how quickly a file starts downloading and how server resources are used during the download process.
Serving a file for user download in an Express app
Express
app.get('/file', (req, res) => {
  res.download('/path/to/file.pdf', 'file.pdf', err => {
    if (err) res.status(500).send('Error downloading file');
  });
});
Streams the file directly to the response, freeing memory and allowing faster download start.
📈 Performance GainNon-blocking, low memory use, faster response start
Serving a file for user download in an Express app
Express
app.get('/file', (req, res) => {
  const file = fs.readFileSync('/path/to/file.pdf');
  res.setHeader('Content-Disposition', 'attachment; filename="file.pdf"');
  res.send(file);
});
Reads the entire file into memory before sending, blocking the event loop and increasing memory use.
📉 Performance CostBlocks server during read, high memory usage for large files, slower response start
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
res.send with fs.readFileSync0 (server-side only)00[X] Bad
res.download streaming file0 (server-side only)00[OK] Good
Rendering Pipeline
The server streams the file data directly to the client without buffering the entire file, minimizing server blocking and memory pressure.
Server File I/O
Network Transfer
⚠️ BottleneckServer File I/O if file is large or on slow disk
Optimization Tips
1Stream files with res.download to reduce server memory use and speed up download start.
2Avoid reading entire files into memory before sending to prevent blocking the server.
3File downloads do not impact Core Web Vitals related to page rendering.
Performance Quiz - 3 Questions
Test your performance knowledge
Why is using res.download better than reading the file fully into memory before sending?
ABecause res.download streams the file, reducing memory use and speeding up response start
BBecause res.download compresses the file automatically
CBecause res.download caches the file in the browser
DBecause res.download encrypts the file during transfer
DevTools: Network
How to check: Open DevTools, go to Network tab, request the file download endpoint, and observe the timing and size of the response.
What to look for: Look for fast 'Time to First Byte' and steady data transfer indicating streaming rather than delayed full buffering.