0
0
Expressframework~30 mins

Why serving static files matters in Express - See It in Action

Choose your learning style9 modes available
Why serving static files matters
📖 Scenario: You are building a simple website using Express.js. Your website needs to show images, styles, and scripts to visitors. These files are called static files because they do not change often. To make your website work well, you need to tell Express where to find these static files.
🎯 Goal: Learn how to serve static files in Express.js by setting up a folder for static content and configuring Express to use it. This will help your website show images, CSS, and JavaScript files correctly.
📋 What You'll Learn
Create a folder named public to hold static files
Set up Express to serve static files from the public folder
Use the express.static middleware correctly
Add a simple route to test the server
💡 Why This Matters
🌍 Real World
Serving static files is essential for websites to show images, styles, and scripts correctly. This setup is common in web projects.
💼 Career
Understanding how to serve static files with Express is a basic skill for backend web developers and helps in building full-stack applications.
Progress0 / 4 steps
1
Create the Express app and import express
Write code to import express and create an app variable by calling express().
Express
Need a hint?

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

2
Create a public folder for static files
Create a folder named public in your project directory to hold static files like images, CSS, and JavaScript. Then, add a variable staticPath and set it to the string 'public'.
Express
Need a hint?

Just create a string variable named staticPath with the value 'public'.

3
Use express.static middleware to serve static files
Use app.use() with express.static(staticPath) to tell Express to serve static files from the public folder.
Express
Need a hint?

Use app.use(express.static(staticPath)) to serve files from the folder.

4
Add a simple route and start the server
Add a route for GET / that sends the text 'Welcome to static files demo'. Then start the server on port 3000 using app.listen.
Express
Need a hint?

Use app.get to create a route and app.listen(3000) to start the server.