How to serve CSS files in Node.js
To serve CSS files in a Node.js application, you'll typically use the express
framework along with the built-in path
module to correctly serve static files like CSS. Here's a step-by-step guide:
Step 1: Set Up the Project
-
Initialize a Node.js project: If you haven't already initialized a Node.js project, you can do so by running:
npm init -y
-
Install Express: You need to install the
express
package, which makes it easier to serve static files.npm install express
Step 2: Create the Directory Structure
For this example, let's create the following directory structure:
project-root/
│
├── public/
│ └── styles.css
├── server.js
└── index.html
public/
: This folder will contain your static files, including CSS.styles.css
: Your CSS file.server.js
: The main server file.index.html
: An HTML file to test the CSS.
Step 3: Create the CSS File
In public/styles.css
, add some basic styles:
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
}
h1 {
color: #333;
text-align: center;
margin-top: 50px;
}
Step 4: Create the HTML File
Create an index.html
file in the project root:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Node.js CSS Example</title>
<link rel="stylesheet" href="/styles.css">
</head>
<body>
<h1>Hello, Node.js!</h1>
</body>
</html>
Step 5: Create the Server
In the server.js
file, set up an Express server to serve the static files:
const express = require('express');
const path = require('path');
const app = express();
// Serve static files from the "public" directory
app.use(express.static(path.join(__dirname, 'public')));
// Serve the index.html file
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'index.html'));
});
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
Step 6: Run the Server
Start your server by running:
node server.js
Step 7: Access the Application
Open your browser and navigate to http://localhost:3000
. You should see the HTML page styled with the CSS file.
How It Works
express.static()
: This middleware function serves static files from the specified directory (in this case,public
). This is where the CSS file is located.app.get('/', ...)
: This route serves theindex.html
file when you visit the root URL.
By following these steps, your Node.js application will be able to serve CSS files and any other static assets you place in the public
directory.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.