Share
Explore

Node.js Lab: Serving Static Files with Express.js


#### Objective: In this lab, students will learn how to use the static middleware in Express.js to serve static files such as HTML, CSS, and images from a public directory.
By the end of this lab, students will be able to set up an Express.js server that serves a static HTML file styled with CSS and includes static images.
---
### Prerequisites: - Basic knowledge of Node.js and Express.js - Node.js installed on your machine
---
### Step-by-Step Guide
#### Part 1: Setting Up the Project
1. **Create a Project Directory:** ```bash mkdir express-static-lab cd express-static-lab ```
2. **Initialize a New Node.js Project:** ```bash npm init -y ```
3. **Install Express:** ```bash npm install express ```
Part 2: Setting Up the Directory Structure
1. **Create the Following Directory Structure:** ``` express-static-lab ├── public │ ├── css │ │ └── styles.css │ ├── images │ │ └── logo.png │ └── index.html ├── server.js └── package.json ```
2. **Add Content to the Static Files:**
- **`public/index.html`:** ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Express Static Files</title> <link rel="stylesheet" href="/css/styles.css"> </head> <body> <header> <img src="/images/logo.png" alt="Logo"> <h1>Welcome to Express Static Files Lab</h1> </header> <main> <p>This is a sample static HTML file served by Express.js</p> </main> </body> </html> ```
- **`public/css/styles.css`:** ```css body { font-family: Arial, sans-serif; background-color: #f4f4f4; margin: 0; padding: 0; display: flex; flex-direction: column; align-items: center; }
header { background-color: #333; color: white; padding: 20px; text-align: center; width: 100%; }
main { padding: 20px; text-align: center; }
img { max-width: 100px; height: auto; } ```
- **`public/images/logo.png`:** Use any sample image or logo image for this file. You can download a small logo image from the web and place it in the `public/images/` directory as `logo.png`.

Part 3: Creating the Express Server

1. **Create and Configure `server.js`:** ```javascript const express = require('express'); const path = require('path'); const app = express(); const port = 3000;
// Middleware to serve static files app.use(express.static(path.join(__dirname, 'public')));
app.listen(port, () => { console.log(`Server running at http://localhost:${port}`); }); ```
#### Part 4: Running the Server
1. **Start the Server:** ```bash node server.js ```
2. **Open Your Browser and Navigate to:** ``` http://localhost:3000 ```
You should see the static HTML file styled with CSS and the image displayed as part of the page.
---
### Detailed Explanation
#### 1. Setting Up Express Server
- **Express Initialization:** - We start by requiring the `express` module and initializing an Express application. - We define the port the server will listen on, in this case, port `3000`.
- **Serving Static Files:** - `express.static` middleware is used to serve static files. - We set the `public` directory as the location for our static files. - `path.join(__dirname, 'public')` constructs the path to the `public` directory relative to the location of `server.js`.
- **Starting the Server:** - `app.listen(port, () => {...})` starts the server and listens on the specified port.
#### 2. Directory Structure
- **Public Directory:** - Contains all static assets: HTML, CSS, images, and any other files that should be accessible to clients.
- **HTML File (`public/index.html`):** - Serves as the main webpage, linking to the CSS file and including an image. - The `link` tag in the `<head>` section references the CSS file. - The `img` tag in the `<body>` references the image file.
- **CSS File (`public/css/styles.css`):** - Provides styling for the HTML elements. - Simple styles to demonstrate the effect of serving static CSS.
- **Image File (`public/images/logo.png`):** - Included in the HTML to demonstrate serving static image files.
#### 3. Running and Testing
- **Starting the Server:** - `node server.js` starts the Express server. - The static middleware makes all files in the `public` directory accessible at the root URL.
- **Accessing the Files:** - Navigating to `http://localhost:3000` displays the `index.html` file styled with `styles.css` and including the `logo.png` image.
### Conclusion
By the end of this lab, students will have learned how to: - Set up a basic Express.js server. - Use static middleware to serve static files. - Organize static assets in a public directory. - Serve HTML, CSS, and image files from an Express.js server.
This foundational knowledge is essential for building more complex web applications where static assets need to be efficiently served alongside dynamic content.
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.