NodeJS : Displaying HTML from file with Example

NodeJS is server side program it can return HTML pages based on user requirements. We can able to load HTML files instead of rendering HTML contents. There is a function sendFile() it accepts file path as argument and returns rendering file.

Syntax:

app.get('/PATH', function (req, res) {
  res.sendFile( __dirname + "/" + "FILE NAME" );
});

 

Example File structure:

place file as shown below,

- main.js
- links.html

Execution:

// Goto the directory that main.js and run below command in command prompt or terminal.
Drive://Path to Source file >node main.js
Example app listening at :::8081 Port

Output:

pic3.JPG

Example Code:

main.js

var express = require('express');
var app = express();
 
// Running Server Details.
var server = app.listen(8081, function () {
  var host = server.address().address;
  var port = server.address().port;
  console.log("Example app listening at %s Port", port);
});
 
app.get('/links', function (req, res) {
  res.sendFile( __dirname + "/" + "links.html" );
});

links.html

<html>
  <body>
    <ul>
      <li><a href="http://www.google.com">Google</a></li>
      <li><a href="http://www.facebook.com">Facebook</a></li>
      <li><a href="http://www.twitter.com">Twiter</a></li>
    </ul>
  </body>
</html>
Category: