Async or Sync bcrypt function to use in node.js in order to generate hashes?

Viewed 7642

I'm currently trying to make authentication module for my project in node.js?

I've already seen some examples of using bcrypt to generate hashes, i.e.

https://github.com/bnoguchi/mongoose-auth/blob/master/lib/modules/password/plugin.js https://github.com/Turbo87/locomotive-passport-boilerplate/blob/master/app/models/account.js

However, for some reason they are using bcrypt.hashSync() function. Since bcrypt is good because it's time-consuming, wouldn't it be wiser to use asynchronous function instead in order to not block the code, i.e:

User.virtual('password')
.get( function () {
    return this.hash;
})
.set( function (password) {
    bcrypt.hash('password', 10, function(err, hash) {
        this.hash = hash;
    });
});

Could you please explain me which way is better and why? Thank you!

3 Answers

Here's a benchmark that shows async hash() is 2.3x faster than synchronous hashSync(): https://jinoantony.com/blog/async-vs-sync-nodejs-a-simple-benchmark

I don't really know what's the reason for this speed-up given that the function is strictly CPU-bound, no I/O. Maybe the async version is able to utilize multiple cores under the hood? This could be a likely explanation. I ran this benchmark myself and got a consistent 4x speed-up on a machine with 8 cores.

Related