Best practie to require a module within Sails.js globally?

Brimstone picture Brimstone · Jan 13, 2014 · Viewed 7.3k times · Source

I am currently building out the Authentication piece of my Sails.js app, using bcrypt to hash my passwords. Everything is working well, here is a sample of the implementation thus far:

beforeCreate: function (values, next) {

    require('bcrypt').hash(values.password, 10, function passwordEncrypted(err, encryptedPassword) {

        if (err) return next(err);

        values.password = encryptedPassword;
        next();

    });

}

Now, both in my model and in my controller, I am using require('bcrypt') or var bcrypt = require('bcrypt'); so I can use it within my class.

I am looking for a better practice way of defining var bcrypt = require('bcrypt'); once and globally so that I can simply use the bcrypt variable whenever I need to (inside other models or controllers).

I am inclined to believe that Sails.js already has something in place for that? If not, what do you suggest the best route of implementation? In the end, I am looking for best practice.

Thanks in advance!

Answer

bredikhin picture bredikhin · Jan 13, 2014

Since Node.js modules are cached once they are loaded for the first time, reusing require('bcrypt') or not won't make any difference in terms of performance.

That said, if you are still up for doing it your way, you can require bcrypt in config/bootstrap.js and add it to the sails namespace:

module.exports.bootstrap = function (cb) {
  sails.bcrypt = require('bcrypt');

  //...

  cb();
}

After that you'll be able to use sails.bcrypt in your controllers or models.