How to work with static template rendering in Hapi Js Framework

Views

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 Write and Run Your Firs …

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
Views

Getting Started with PM2, the …

Getting Started with PM2, the Node.js Process Manager. PM2, or Process Manager 2 is an incredibly versatile production process manager written in Node.js.Restarting after crashes: PM2 allows us to keep processes running until the heat death of the un …

read more
Views