How to serve HTML files in Node.js
To serve HTML files in Node.js, you typically use the http
or express
module. Below are examples of how to serve an HTML file using both methods.
1. Serving HTML with the http
Module
Here's a simple example of serving an HTML file using the built-in http
module in Node.js:
const http = require('http');
const fs = require('fs');
const path = require('path');
const server = http.createServer((req, res) => {
// Set the file path to the HTML file
const filePath = path.join(__dirname, 'index.html');
// Read the HTML file
fs.readFile(filePath, (err, content) => {
if (err) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.end('Server Error');
} else {
// Serve the HTML content
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(content);
}
});
});
// Start the server
server.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
In this example:
- The
http.createServer()
method creates an HTTP server. - The
fs.readFile()
method reads theindex.html
file. - The server sends the HTML file as a response to the client.
2. Serving HTML with the express
Module
Using the express
framework simplifies serving static files, including HTML:
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')));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// Start the server
app.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
In this example:
- The
express.static()
middleware serves static files like HTML, CSS, and JavaScript from a specified directory (public
in this case). - The
res.sendFile()
method sends the HTML file to the client.
Explanation
- http Module: It's a basic way to serve HTML files and requires manual handling of file paths and MIME types.
- express Module: Provides a more straightforward approach with built-in methods for serving static files, making it easier to work with larger projects.
You can use either method depending on the complexity of your application. Express is preferred for more extensive projects due to its simplicity and additional features.
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.