EN
Express.js - send HTML file in response
0
points
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: