Harnessing Hapi.js for Server-Side Development and Static Content
Written on
Chapter 1: Introduction to Hapi.js
Hapi.js is a lightweight framework for Node.js, specifically designed for building backend web applications. In this guide, we will explore how to utilize Hapi.js for backend app development.
To change the context of this within a server method, we can use the bind option.
For instance, consider the following code snippet:
const Hapi = require('@hapi/hapi');
const log = function() {
return this.foo;
};
const init = async () => {
const server = Hapi.server({
port: 3000,
host: '0.0.0.0'
});
server.method('log', log, { bind: { foo: 'bar' } });
server.route({
method: 'GET',
path: '/',
handler(request, h) {
return server.methods.log();}
});
await server.start();
console.log('Server running on %s', server.info.uri);
};
process.on('unhandledRejection', (err) => {
console.log(err);
process.exit(1);
});
init();
In this example, we invoke the server.method function with a third argument that includes the bind property. The value of this inside the log function is determined by the bind property. Therefore, when we call server.methods.log(), it returns 'bar', as this corresponds to this.foo. When a GET request is made to the root path, the response will be 'bar'.
Section 1.1: Serving Static Files
We can serve static files by utilizing the @hapi/inert module. Below is how we can achieve this:
const Hapi = require('@hapi/hapi');
const Path = require('path');
const init = async () => {
const server = Hapi.server({
port: 3000,
host: '0.0.0.0',
routes: {
files: {
relativeTo: Path.join(__dirname, 'public')}
}
});
await server.register(require('@hapi/inert'));
server.route({
method: 'GET',
path: '/',
handler(request, h) {
return h.file('./pic.png');}
});
await server.start();
console.log('Server running at:', server.info.uri);
};
process.on('unhandledRejection', (err) => {
console.log(err);
process.exit(1);
});
init();
In this case, we create the server with the routes.files.relativeTo option, setting it to the path of our static files using Path.join. We register the @hapi/inert plugin and render the static file using the h.file method in our route handler. Thus, accessing the root path will display the pic.png image located in the public folder.
Subsection 1.1.1: File Handler Implementation
We can also implement the file handler to serve static files as follows:
const Hapi = require('@hapi/hapi');
const Path = require('path');
const init = async () => {
const server = Hapi.server({
port: 3000,
host: '0.0.0.0',
routes: {
files: {
relativeTo: Path.join(__dirname, 'public')}
}
});
await server.register(require('@hapi/inert'));
server.route({
method: 'GET',
path: '/',
handler: {
file: './pic.png'}
});
await server.start();
console.log('Server running at:', server.info.uri);
};
process.on('unhandledRejection', (err) => {
console.log(err);
process.exit(1);
});
init();
Here, the handler is replaced with an object specifying the path to our static file.
Section 1.2: Directory Handler Usage
Additionally, we can serve files from a directory using the directory handler, as shown below:
const Hapi = require('@hapi/hapi');
const Path = require('path');
const init = async () => {
const server = Hapi.server({
port: 3000,
host: '0.0.0.0',
});
await server.register(require('@hapi/inert'));
server.route({
method: 'GET',
path: '/{param*}',
handler: {
directory: {
path: Path.join(__dirname, 'public')}
}
});
await server.start();
console.log('Server running at:', server.info.uri);
};
process.on('unhandledRejection', (err) => {
console.log(err);
process.exit(1);
});
init();
In this implementation, the path /{param*} allows us to specify the filename of the requested file. The handler.directory.path property is set to the directory containing the static files.
Chapter 2: Conclusion
In summary, we can alter the value of this within a server method using the bind property. Additionally, static files and directories can be served effectively with the @hapi/inert module.
Explore the Hapi JS tutorial on serving static files to deepen your understanding of the subject.
Watch this Hapi.js Framework Crash Course to get a comprehensive overview of Hapi.js functionalities.