Consider this Express route handler:
app.get('/file', (req, res) => {
res.download('/files/report.pdf');
});What is the expected behavior when a client requests /file?
app.get('/file', (req, res) => { res.download('/files/report.pdf'); });
Think about what res.download is designed to do with files.
res.download sends the file as an attachment, which usually triggers the browser's download dialog. It does not display the file inline or send JSON.
You want to send a file located at /files/data.csv but want the browser to save it as export.csv. Which code snippet does this correctly?
Check the order of parameters in res.download.
The second parameter to res.download is the name the file should have when downloaded. Option A uses the correct order.
Look at this code snippet:
app.get('/download', (req, res) => {
res.download('/files/missing.pdf');
});The file missing.pdf does not exist. What error will Express send to the client?
app.get('/download', (req, res) => { res.download('/files/missing.pdf'); });
Think about how Express handles missing files in res.download.
If the file is missing, Express automatically sends a 404 Not Found error to the client.
Consider this code:
app.get('/file', (req, res) => {
res.download('/files/report.pdf', (err) => {
if (err) {
console.error('Download failed:', err);
res.status(500).send('Error occurred');
}
});
});What happens if the file is successfully sent?
app.get('/file', (req, res) => { res.download('/files/report.pdf', (err) => { if (err) { console.error('Download failed:', err); res.status(500).send('Error occurred'); } }); });
Callbacks in res.download are called after the transfer attempt.
The callback runs after the download attempt. If no error occurs, the callback receives null and no further action is needed.
Choose the correct statement about res.download in Express.
Think about what Content-Disposition header does for downloads.
res.download sets the Content-Disposition header to 'attachment' and includes the filename, prompting browsers to download the file.