How to render plain text of HTML in Node.js ?
Last Updated :
10 Oct, 2021
Express Js is the web application framework based on Node.js web server functionality that helps us to create the application endpoints that respond based on the HTTP request (POST, GET, etc) method and the requested route. The res.sendFile() method of the express.js module is used to render a particular HTML file that is present in the local machine.
Syntax:
res.sendFile(path,[options],[fn])
Parameters: The path parameter describes the path and the options parameter contains various properties like maxAge, root, etc and fn is the callback function.
Returns: It returns an Object.
Project Setup:
Step 1: Install Node.js if Node.js is not installed in your machine.
Step 2: Create a new folder named public, inside the public folders. Create two files named index.html and products.html inside the public folder.
Step 3: Now, initialize a new Node.js project with default configurations using the following command on the command line.
npm init -y
Step 5: Now install express inside your project using the following command on the command line.
npm install express
Project Structure: After following the steps your project structure will look like.
app.js
const express = require( 'express' );
const path = require( 'path' );
const app = express();
app.get( '/' , (req, res) => {
res.sendFile(path.join(__dirname, '/public/index.html' ));
});
app.get( '/products' , (req, res) => {
res.sendFile(path.join(__dirname, '/public/products.html' ));
});
app.listen(3000, () => {
console.log( 'Server is up on port 3000' );
});
|
index.html
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "UTF-8" />
< meta http-equiv = "X-UA-Compatible" content = "IE=edge" />
< meta name = "viewport" content =
"width=device-width, initial-scale=1.0" />
< title >HTML render demo</ title >
</ head >
< body >
< h1 >Home page</ h1 >
</ body >
</ html >
|
products.html
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "UTF-8" />
< meta http-equiv = "X-UA-Compatible" content = "IE=edge" />
< meta name = "viewport" content =
"width=device-width, initial-scale=1.0" />
< title >HTML render demo</ title >
</ head >
< body >
< h1 >Products page</ h1 >
</ body >
</ html >
|
Run app.js file using below command:
node app.js
Output: Open the browser and go to http://localhost:3000, and manually switch to http://localhost:3000/products and you will see the following output.
Share your thoughts in the comments
Please Login to comment...