Languages
[Edit]
EN

Node.js / Express.js - send HTML file in response

0 points
Created by:
Mikolaj
249

In this article, we would like to show you how to send HTML file in response in express.js.

1. Import path module

To deal with file paths you need to import the node.js path module using the following command:

const path = require('path');

2. Use res.sendFile() method

In below example we:

  • Use the res.sendFile() method within the request. The method takes the path argument.
  • Use path.join() to specify the path argument:
    • __dirname - current directory

    • 'index.html' - the HTML file we want to send

Now our path inside res.sendFile() method looks like this: C:\project\index.html

When the project folder looks like this

/C/
 └── project/
      │
      ├── index.js
      ├── index.html
      ├── package.json
      └── package-lock.json

Pracrical example:

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

const app = express();

// set HTML file as a response 
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'index.html'));
});

app.listen(5000);

Result:

Node.js / Exoress.js - HTML file as a response
Node.js / Exoress.js - HTML file as a response
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join