To serve an HTML file over an Express server, we’ll need the use of the res.sendFile()
method. It is used to deliver files over the server.
As a result in this article, I will teach you the easy and simple way to send an HTML file over an express server.
Step 1: Initialize the Express server
-
Install Express dependency to your Node.js project if you haven’t:
npm i express # Using NPM yarn add express # Using Yarn
-
Inside
index.js
orserver.js
add the following code,const express = require("express") const app = express() app.get("/", (req, res) => { res.send({ message: "Hello World" }) }) app.listen(3000);
Now, you have successfully initialized the Express server running at port 3000.
Step 2: Add an HTML File to the server
-
Inside the root directory, create a file
views/index.html
:<html> <head> <title>This is an Express App</title> </head> <body> <h1>This page is fetched from the Express Server</h1> </body> </html>
You can replace this file with your HTML code. This code is just for demo purposes.
-
Now inside the
index.js
orserver.js
add the following code:let absolutePath = __dirname + "/views/index.html" app.get("/", (req, res) => { res.sendFile(absolutePath) })
Here, you might be thinking, where did this
__dirname
come from? Let me explain…What is __dirname?
__dirname
is an environment variable that tells you the absolute path of the directory containing the currently executing file.You have successfully served an HTML file to an Express server.
Conclusion
In conclusion, serving an HTML file over an Express server is straightforward. Following the above steps, you can easily add an HTML file to the server and send it as a response using the res.sendFile()
method. This method allows you to deliver any file type, including images, PDFs, and videos. Express.js is an efficient and popular web application framework that can help you build robust and scalable web applications. You can now continue to explore and experiment with Express to create more complex web applications.
Thanks for reading :)