0

I have node.js code mentioned below:

    router.post("/addData", async (req, res)=>{
      const password = req.body.password;
      console.log("before.password: ", password);
      await bcrypt.genSalt(10, (err, salt) => {
        bcrypt.hash(password, salt, (err, hash) => {
          if (err) {
            console.log("bcrypt error: ", err);
          }
          console.log("hash passw: ", hash);
          password = hash;
        });
      });
      console.log("after.password: ", password);
});

Actual output is:

before.password: passw 
after.password: passw 
hash passw:  $2a$10$TWiXiJQK2abV1T2fvH.nIuqCYKNrMDYaz2PHpATswIVDPYsMw/QsG

I need output which is expected output as shown below:

before.password: passw 
hash passw:  $2a$10$TWiXiJQK2abV1T2fvH.nIuqCYKNrMDYaz2PHpATswIVDPYsMw/QsG 
after.password: $2a$10$TWiXiJQK2abV1T2fvH.nIuqCYKNrMDYaz2PHpATswIVDPYsMw/QsG

When print password out of the bcrypt block, then we get plain password not hashed, I know that bcrypt is working and password is hashed successfully but we cannot get hashed password out of the bcrypt block.

Please help me regarding to the same question, I think I misplace code at some point. Thanks in advance.

Liam
  • 27,717
  • 28
  • 128
  • 190

1 Answers1

2

You are using two methods to deal with async code. When you do

bcrypt.genSalt(10, (err, salt) => { 
  // callback code here
})

you are using a callback. Callback is a function that is executed when the genSalt function has finished. So you're telling the program: "when genSalt has finished run this code"

The other way to handle async code is to use promises with async/await. So basically you say: "wait for this and return me the value"

const hash = await bcrypt.genSalt(10) // waiting for promise, no callback.

In your code you are doing both versions.

Also note that bcrypt also has the genSaltSync and hashSync method. So you could do something like:

router.post("/addData", (req, res)=>{
      const password = req.body.password;
      console.log("before.password: ", password);
      const salt = bcrypt.genSaltSync(10);
      const hash = brypt.hashSync(password,salt)
      console.log("after.password: ", hash);
});

Notice in this example that the handler doesn't have async keyword. Since we are using synchronous methods.

Bergur
  • 3,962
  • 12
  • 20
  • Just a remark, bcrypt `genSalt` has Promise api so generally you can also generate salt like this `const salt = await bcrypt.genSalt(10);` – Logans Sep 04 '18 at 10:54
  • Yeah sorry was editing my post to show the same thing :) – Bergur Sep 04 '18 at 10:56