What is the difference between hapi.js and nodejs plugins

I just started getting to know Hapi. Hapi uses plugins to add components to your application. I am having a hard time figuring out why I would use plugins when I can just do something like:

var lib = require('whatever lib from npm');

      

What is the difference between the two?

+3


source to share


1 answer


Hapi plugins are also node modules, but they are node modules that were built according to the Hapi Plugin API (they expose a registration method that registers the plugin with your Hapi package / server)

Plugins can automatically add routes to your server, modify the request, payload, and response, and in general can modify the behavior of Hapi.

So, short plugins are node modules written specifically to increase Hapi.

Let's look at two packages lout

and Lo-Dash

. Lo-Dash

as you know it is a js high performance toolbox. lout

is a Hapi plugin that will add the / doc route to your application. you can find both on npm and start with lout

-

var Hapi   = require('hapi'),
    lout   = require('lout'),      
    server = new Hapi.Server(80);  

server.pack.register({ 
        plugin: lout
    }, function() {
        server.start();
    }
);

      

As you can see All we have to do is register lout with our server package and all its magic is available to us (some plugins will require more options)



can now be used lodash

in our code

var Hapi   = require('hapi'),
    lout   = require('lout'),
    _      = require('lodash'),
    preset = { app: { name: "myApp"}},
    server;

if (process.env.DEBUG) {
    _.extend(preset, {debug: {request: ['error']});
}

server = new Hapi.Server(80, preset);

_.extend(preset, { endpoint: '/lout'});
server.pack.register({ 
        plugin: lout
    }, function() {
        server.start();
    }
);

      

here we use lodash

to extend the server settings and configure our server to log errors to the console if we set the DEBUG environment parameter when starting the server. please note that lodash

he has no idea about our Hapi server and how it works, it is just used as a helper and the programmer needs to know how to stitch them together.

Calling lodash

from server.pack.register

is meaningless and will result in an error. So this work doesn't work -

server.pack.register({ 
        plugin: require('lodash')
    }, function() {
        server.start();
    }
);

      

+6


source







All Articles