Express.js is a flexible node framework that simplifies the process of creating web applications. With Express, you can easily serve your application to the users' browsers. Let's see how you can serve HTML files to the browser using Express.

Prerequisites

  • To follow along, make sure you have Node.JS and npm installed on your machine.
  • You also need a basic understanding of Node.

Setting up the Project

To serve HTML files to the browser using Express, we'll need to install the required dependencies and set up a simple server. This tutorial won't go in-depth into explaining express but we'll create a simple server and explain what each line of code means.

Learn more about creating an express server in this article.

How to Create a NodeJS Server Using Express
Learn how to create a node.js server using the Express framework and define different routes to handle the GET requests.

To get started, navigate to where you want to start your project and create a new directory. I will call my directory serve_html. You can name it anything you want. Once the folder is created, go into the folder. You can achieve that using the command below.

mkdir serve_html && cd serve_html

Once you are in the folder, create the entry point for the project. I will call my entry file app.js. Create the files using the touch command.

touch app.js

With the Entry point created, initialize a new node project with the command below.

npm init

This command will create a package JSON file that will store all the dependencies we use.

Let's now install the project's dependencies (express, nodemon). Install them using the command below.

npm install express nodemon

In the package JSON file, edit the scripts as shown below.

Creating the server

Open the app.js file and import the dependencies as shown below.

const express = require('express');
const app = express();

The code above imports the express framework and creates an instance of express. This way we can use the app to create new routes.

Add a port number and let the server listen from that port.

const express = require('express');
const app = express();

const port = 3000;


app.listen(port, () => {
    console.log(`Server Running on port: ${port}`);
})

So far we have a working server. Let's now create the HTML to server using the server we have made.

Creating HTML document

On the root directory of your project, create a new folder with the name public and inside that folder, create a index.html file. You can achieve that with the command below.

mkdir public && cd public && touch index.html

Open the index.html file and write your HTML. In this demo, I will write something simple.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Serve HTML</title>
</head>
<body>
    <h1>Serving HTML files Using Express</h1>
    <p>You have successfully served your files to the browser.</p>
</body>
</html>

This is the file we will serve to the browser.

Serving Static files using express

Go back to the app.js file and add the following code below the port number.

app.use(express.static("public"));

app.get ("/", (req, res) => {
    res.sendFile("/public/index.html");
});

The first line of this code uses express.static middleware to serve static files such as HTML and CSS. We have set this middleware to serve files from the "public" folder.

The next line defines a new route for the root URL "/". When a user goes to this URL (http://localhost:3000/), they should be able to see our HTML. This is made possible by Express which receives the request using the app.get method. The response is sent inside a callback function. This response is sent using the (res.sendFile) method. Inside this method, we add the path to the index.html file.

So far this is the code we have in the app.js file.

const express = require('express');
const app = express();

const port = 3000;

app.use(express.static("public"));

app.get ("/", (req, res) => {
    res.sendFile("/public/index.html");
});

app.listen(port, () => {
    console.log(`Server Running on port: ${port}`);
})

Here is the folder structure so far.

/express-html/
-- public/
   -- index.html
-- app.js
-- package.json

Running the Application

After running our code, we should be able to see our HTML in the browser if everything went as planned.

To run your application, use the command below.

npm start

The command above starts the server. We can now visit http://localhost:3000/ and find out if everything went well.

Output:

Congratulations, you have successfully served HTML files using an Express Server.

Wrapping up

Serving static files using Express is fundamental in node development. This article has shown you how you can serve HTML files to the browser without any trouble. This is just the tip of the iceberg. Express offers many more features, and middleware for handling various aspects of development.

If you found this article helpful, please share it, and good luck in your development journey.

Thanks for reading : )

Table of Contents
Great! Next, complete checkout for full access to GeekBits.
Welcome back! You've successfully signed in.
You've successfully subscribed to GeekBits.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info has been updated.
Your billing was not updated.