Search code examples
node.jsasynchronousbcrypt

Is there a code pattern to return bcrypt hash created with async function to a separate module?


Is there an elegant way to return a bcrypt hash value to a separate module?

In the example below function hashPassword() uses bcrypt to hash a password. It is located in the file hashpassword.js. I'd like to return its hash value to the variable myHashedPassword in app.js. I'm sure there must be a brute force way to do this. But is there any sort of clever or elegant way to return the value?

app.js

let password = '123';
let myHashedPassword = hashPassword(password);

hashpassword.js

function hashPassword(password) {
    bcrypt.genSalt(10, function(error, salt) {
        bcrypt.hash(password, salt, function(error, hash) {
            // In most cases at this point hash is saved to the database.
            // However is there a pattern to return its value to the outer function and then app.js?
            // With this being async is that even possible?
        });
    }); 
}

Solution

  • The bcrypt package has synchronous equivalents to the functions you are using, see example. If you still want to leverage the async versions, then you would need to return a Promise which you can then await e.g.

    function hashPassword(password) {
      return new Promise((resolve, reject) => {
        bcrypt.genSalt(10, (error, salt) => {
          if (error) return reject(error);
    
          bcrypt.hash(
            password, 
            salt, 
            (error, hash) => err ? reject(err) : resolve(hash)
          );
        }); 
      });
    }
    ...
    let hashed = await hashPassword(password);
    

    In terms of then exporting in a way that the consumer simply calls the function, if using ES6 or newer

    export default function hashPassword(password) {
      ...
    }
    

    Otherwise

    function hashPassword(password) {
      ...
    }
    
    module.exports = hashPassword