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

2

1 Answer 1

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); 
Sign up to request clarification or add additional context in comments.

7 Comments

This would be considered 'blocking', but could bcrypt.compareSync be used here?
@zer0kompression yes, but don't. It's a serious de-optimization that's no longer even syntactically advantageous with the addition of async / await to the ES7 specification.
Yes, I understand the asyn now. I was new to node. Thanks. its working.
@zer0kompression Yes, it could and yes, you are right, it is a 'blocking' operation and you can access the result literally in the same line of code without using callbacks, but for the price of performance drawbacks.
@PatrickRoberts Thank you for pointing about undefined. Updated my post to fix it.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.