Categories
Hapi

Server-Side Development with Hapi.js — this and Server Methods and Static Files

Spread the love

Hapi.js is a small Node framework for developing back end web apps.

In this article, we’ll look at how to create back end apps with Hapi.js.

Bind

We can change the value of this inside our server method with the bind option.

For example, we can write:

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();

We call the server.method method with the 3rd argument with the bind property.

Whatever the value of bind is the value of this inside the log function.

So when we call server.methods.log , we have 'bar' returned since it’s the value of this.foo .

And when we make a GET request to the / route, we get bar returned as the response.

Serving Static Content

We can serve static content with the @hapi/inert module.

For example, we can write:

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();

We create the server with the routes.files.relativeTo option.

We set the relativeTo property with the Path.join method to get the path to our static files.

Then we register the @hapi/inert plugin with:

await server.register(require('@hapi/inert'));

And we in our route handler, we get render the static file by using the h.file method.

Now when we go to the / route, we see the pic.png image we uploaded to the public folder.

File Handler

We can also use the file handler to serve our static file by writing:

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();

We replaced the handler method with an object with the path to our static file.

Directory Handler

Also, we can serve files from a directory by using the directory handler.

For instance, we can write:

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();

We have the ‘/{param*}’ path to let us pass in the file name of the file to get.

Then we set the handler.directory.path property to set the path which has the static files.

Conclusion

We can change the value of this in a server method with the bind property.

And we can serve static files and directories with the @hapi/inert module.

Leave a Reply

Your email address will not be published. Required fields are marked *