1

I am trying to store the hash password and checking the it is valid or not.

var bcrypt = require('bcrypt');
let data = "";

bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash("my password", salt, function(err, hash) {
        // Store hash in your password DB.
        console.log(hash);
        data = hash;
    });
});

bcrypt.compare("my password", data, function(err, res) {
    // res === true
    console.log(res)
});

return value always false.?

but if I move the compare inside genSalt function its returning true.

Thanks

Vish K
  • 135
  • 5
  • 14
  • 3
    Because `data === ""`. Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Patrick Roberts Mar 14 '18 at 04:06
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – coagmano Mar 14 '18 at 04:43

1 Answers1

2

You are dealing with asynchronous functions in node.js, so this result is expected. For the clearer understanding of the problem try to console.log data before bcrypt.compare. I can certainly say it would be equal to an initial value of "".

Then try to move your compare function inside the .hash callback

var bcrypt = require('bcrypt');
let data = "";

bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash("my password", salt, function(err, hash) {
        // Store hash in your password DB.
        console.log(hash);
        data = hash;
        console.log(data); // Here data equals to your hash
        bcrypt.compare("my password", data, function(err, res) {
            // res === true
            console.log(res)
        });
    });
});
console.log('data') // Here data equals to initial value of ""

You can use async/await functions to make it look like synchronous code and get rid of callbacks. Luckily, bcrypt support promise interface that is used by async/await

const salt = await bcrypt.genSalt(10);
const hash = await bcrypt.hash("my password", salt);
const result = await bcrypt.compare("my password", data);
console.log(result);
coockoo
  • 2,294
  • 17
  • 26