How to work with static template rendering in Hapi Js Framework

Accessing static template or rendering template in Hapi Js framework we need some builtin plugins.like 'inert'

In my previous blog how to install Hapi Js I have installed the Hapi Js framework and start with a simple hello world test example.

Now we want to use static template so we need some plugins for that is called "inert" to serve a static page.

So to install the inert plugins we run the following command at command prompt.

npm install inert --save

This will download the inert plugin and add it to the package.json file as a dependency.

Now create a folder "public" inside the hapi folder to put the static file and create a hello.html file to create some html content here.

Then put the following code into the server.js file

  
'use strict';  

const Hapi = require('hapi');  

//Create a server with a host and port 
const server = new Hapi.Server(); 

server.connection({      
host: 'localhost',      
port: 8000  
});  

//Add the route 

server.register(require('inert'), (err) => {     
if (err) {         
throw err;     
}      

server.route({         
method: 'GET',         
path: '/hello',         
handler: function (request, reply) {             
reply.file('./public/hello.html');         
}     
}); 
});  

// Start the server 
server.start((err) => {     
if (err) {         
throw err;     
}     
console.log('Server running at:', server.info.uri); 
}); 

Here we are using the server.register() function for registering the plugin

When you will open the http://localhost:8000/hello your content will display on the browser.

This technique is commonly used to serve images, stylesheets, and static pages in your web application.

How to make a Node JS application with TypeScript

Sure, here's an example of how you can create a basic Node.js application using TypeScript: 1. **Install Node.js and TypeScript:** First, make sure you have Node.js and npm (Node Package Manager) installed. You can then install TypeScript glob …

read more

How To Write and Run Your First Program in Node.js

How To Write and Run Your First Program in Node.js. Node.js is a popular open-source runtime environment that can execute JavaScript outside of the browser using the V8 JavaScript engine, which is the same engine used to power the Google Chrome web b …

read more