0
0
Expressframework~30 mins

res.download for file downloads in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Using res.download for File Downloads in Express
📖 Scenario: You are building a simple Express server that allows users to download a file from your server.
🎯 Goal: Create an Express route that uses res.download to send a file named example.txt to the user when they visit /download.
📋 What You'll Learn
Create an Express app instance
Create a route handler for GET requests to /download
Use res.download to send the file example.txt
Set a custom filename for the downloaded file as user-file.txt
💡 Why This Matters
🌍 Real World
File downloads are common in web apps for delivering reports, images, or documents to users.
💼 Career
Knowing how to serve files securely and correctly is important for backend developers working with Express.
Progress0 / 4 steps
1
Set up Express app and import modules
Write code to import express and create an Express app instance called app.
Express
Need a hint?

Use require('express') to import Express and then call express() to create the app.

2
Create a GET route for /download
Add a GET route handler on app for the path /download that takes req and res as parameters.
Express
Need a hint?

Use app.get('/download', (req, res) => { ... }) to create the route.

3
Use res.download to send example.txt
Inside the /download route handler, use res.download to send the file example.txt from the current directory. Set the downloaded filename to user-file.txt.
Express
Need a hint?

Use path.join(__dirname, 'example.txt') to get the file path and then call res.download(filePath, 'user-file.txt').

4
Start the Express server
Add code to start the Express server on port 3000 using app.listen.
Express
Need a hint?

Use app.listen(3000) to start the server on port 3000.