Send an HTML File in Node.js Using Express and res.sendFile Explained

Node Js Send HTML File Thumbnail

Ever wondered why a web page sometimes fails to load, or why sending an HTML file in Node.js can feel confusing and unreliable? Many of us struggle to deliver HTML files smoothly from a Node.js server, especially when using Express and its res.sendFile method. Discover how to use res.sendFile in Express to send HTML files efficiently, avoid common errors, and ensure every user request gets the right response.

Express Module

Express module has a method sendFile() which can be used to send HTML files directly from the Node.js server to the browser.

For using the express module it is required to install it using NPM.

Syntax:

npm i express

For more about NPM check: A Beginner’s Guide to Node Package Manager

Create an application to send an HTML file using Node.js

Functionality: A simple Node.js Web App that sends an HTML file for the home page containing an h1 tag with the message “Home” in response to the client.

Approach: We use the “sendFile()” method of Express to send an HTML file to the client when the request receive for the home(“/”) route.

Implementation: Below is the step-by-step implementation for sending an HTML file in Node.js.

Step 1: Create a new folder & open it on code Editor.

Project File

Step 2: Create a file “aap.js” inside that folder.

App Js File

Step 3: Create another file “index.html” which will send as a response to the client.

HTML File

Step 4: Open the terminal & type the below command. This initializes the Node Packages Manager, by which we can install any Node.js framework.

npm init -y

Output:

Npm

Step 5: Inside the terminal, type the below command to install express as a module in the project.

npm i express

Output:

Express

Step 6: Open the “app.js” file and import the express module using the below statement.

const express = require('express');

Step 7: Create a constant “app” and set it to “express()”, which means we are creating an instance of an express module, by which we can call any of the express functions.

const app = express();

Step 8: Then write the following code

app.get('/', (req, res) => {
    
});

Here, we use the express get method, which defines what happens when the client requests for the “/” route, after that we separate it using a comma and pass a callback function.

Inside the callback function, write res.sendFile(), res means response, the response object is used to send different types of data to the client, and the sendFile() is a method of response object by which we send the HTML file as a response.

app.get('/', (req, res) => {
    res.sendFile();
});

If you want to send JSON instead of HTML content, you can use the express’s json() method.

Inside the sendFile method, type the file location that you want to send as a response.

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});

If you are wondering why we use __dirname, you can check out NodeJs Globals where we have explained many global objects including __dirname.

Step 9: After that, create a port in order to test our application on browsers, for this, we will use the express method “listen”, by using our “app” instance and pass a port as an argument which is used to open the application in the browser.

app.listen(3000);

Step 10: Now, open any web browser and type the following, inside the search bar, this opens the Node.js application we set to port 3000.

http://localhost:3000/

Complete Code:

const express = require('express');

const app = express();

app.get('/', (req, res) => {
    res.sendFile(__dirname + '/index.html');
});

app.listen(3000);

Output:

Final Output

Frequently Asked Questions

What does the res.sendFile() function do in Express?

The res.sendFile() function sends a file, such as an HTML file, from the server to the browser, and sets the correct Content-Type based on the file extension.

How do we use res.sendFile() to send an HTML file in a Node.js application?

We use res.sendFile() inside a route handler and provide the path to the HTML file that we want to send to the browser.

Is it necessary to install any package before using res.sendFile()?

Yes, we need to install the express module using the npm install express command before we can use res.sendFile().

Can we send different HTML files for different routes using res.sendFile()?

Yes, we can send different HTML files for each route by calling res.sendFile() with the appropriate file path inside each route handler.

What happens if the file path in res.sendFile() is incorrect or the file does not exist?

If the file path is incorrect or the file does not exist, an error will occur and we can handle it using a callback function with res.sendFile().

What is the difference between res.sendFile() and express.static()?

res.sendFile() is used to send a specific file, while express.static() is used to serve many files from a directory, such as images, CSS, or JavaScript files.

How can we handle 404 errors when a file is not found?

We can add a middleware function at the end of our routes to send a custom message or HTML file when a route or file is not found.

Do we need to use res.render() to send plain HTML files?

No, we do not need to use res.render() for plain HTML files; we can use res.sendFile() to send them directly.

What version of Node.js is required for the latest version of Express?

Express version 5.x requires Node.js version 18 or higher to work properly.

Can we set custom headers when sending files with res.sendFile()?

Yes, we can use the options parameter in res.sendFile() to set custom headers for the response.

Summary

We can send an HTML page while creating a Node.js application, for this, we have to use the express.js module method sendFile(). You can also attach CSS in HTML for custom design. We can send multiple files for different routing requests. You can also read HTML form data using Node.js. We hope this tutorial helps you to render HTML using Node.js.

Reference

https://stackoverflow.com/questions/20345936/nodejs-send-html-file-to-client

Review Your Cart
0
Add Coupon Code
Subtotal