Serving an HTML file in an Express.js
Serving an HTML file in an Express.js server is a common task, especially for beginners. It helps you understand how to set up a basic server and serve static content, which is often the starting point for many web applications. Here’s a step-by-step guide with explanations:
Create a Project Directory: Start by creating a new directory for your project. You can name it whatever you like. For example
mkdir express-html-server
cd express-html-server
Initialize a Node.js Project: Use npm init
to initialize a new Node.js project. Follow the prompts to set up your package.json
file.
npm init -y
Install Express.js: Install Express.js using npm. Express.js is a popular web framework for Node.js, making it easy to build web applications
npm install express
Create an HTML File: Inside your project directory, create an HTML file. This file will be served by your Express.js server. For example, you can create an index.html
file:
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Express HTML Server</title>
</head>
<body>
<h1>Hello, world!</h1>
<p>This is a basic HTML file served by an Express.js server.</p>
</body>
</html>
Create Your Express.js Server
Create a Server File: Create a JavaScript file for your Express.js server. For example, you can name it server.js
.
// server.js
// Import required modules
const express = require('express');
const path = require('path');
// Create an Express application
const app = express();
// Define a route to serve the HTML file
app.get('/', (req, res) => {
// Send the HTML file as the response
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 port ${PORT}`);
});
Explanation:
- We import the
express
module to create an Express application. - The
path
module is used to work with file paths. - We create an Express application using
express()
. - We define a route for the root URL (
/
). When a request is made to this URL, the server responds by sending theindex.html
file. res.sendFile()
is used to send the HTML file as the response.- The server listens on a specified port (
3000
by default) usingapp.listen()
.
Step 4: Run Your Express.js Server
Start the Server: Run your Express.js server by executing the following command in your terminal:
node server.js
Access Your HTML Page: Open your web browser and navigate to http://localhost:3000
. You should see your HTML page served by the Express.js server.
Summary
This setup serves a basic HTML file using Express.js. It’s a fundamental building block for web development, allowing you to understand how to set up a server, define routes, and serve static content. This knowledge forms the foundation for more complex web applications and is essential for beginners to grasp.