Serving static files lets your web app show images, styles, and scripts to users. Without it, your site would look plain and not work well.
You want to show pictures or logos on your website.
You need to apply styles with CSS to make your site look nice.
You want to add JavaScript files to make your site interactive.
You have downloadable files like PDFs or documents for users.
You want to serve fonts or icons for better design.
Syntax
Express
app.use(express.static('public'))
This tells Express to serve all files inside the 'public' folder as static files.
Users can access these files directly via URLs matching their path inside 'public'.
Examples
Serve static files from the 'assets' folder instead of 'public'.
Express
app.use(express.static('assets'))
Serve static files from 'public' but under the '/static' URL path.
Express
app.use('/static', express.static('public'))
Sample Program
This Express app serves files from the 'public' folder. When you visit the home page, it shows a heading and an image loaded from '/logo.png' inside 'public'.
A. express.static is missing the folder path argument
B. app.listen should come before app.use
C. express.static should be called without parentheses
D. The folder name should be 'public' not 'static'
Solution
Step 1: Check express.static usage
express.static is a function that requires the folder path as an argument.
Step 2: Identify missing argument
The code uses express.static without parentheses and folder name, so it won't work.
Final Answer:
express.static is missing the folder path argument -> Option A
Quick Check:
express.static needs folder path argument [OK]
Hint: express.static must be called with folder path [OK]
Common Mistakes:
Forgetting to call express.static as a function
Thinking app.listen order matters here
Assuming folder name must be 'public'
5. You want to serve static files from two folders: public and uploads. Which code correctly serves both folders so files from either can be accessed by URL?
hard
A. app.use(express.static('public'));
app.use(express.static('uploads'));
B. app.use(express.static(['public', 'uploads']));
Express allows multiple static folders by calling app.use(express.static()) multiple times.
Step 2: Evaluate options
app.use(express.static('public'));
app.use(express.static('uploads')); correctly calls express.static twice for each folder. app.use(express.static(['public', 'uploads'])); is invalid syntax. app.use(express.static('public/uploads')); tries to serve a combined folder that likely doesn't exist. app.static('public');
app.static('uploads'); uses a wrong method.
Final Answer:
app.use(express.static('public'));
app.use(express.static('uploads')); -> Option A