1

Summary

I have a function where I use crypto.randomBytes to generate a token and I'm having trouble returning the token from the function. I want to return token from createResetToken. My function is below and I've tried many different things but they aren't working. Any help would be greatly appreciated!

Code

function createResetToken() {
  crypto.randomBytes(20, function(err, buf) {
    const token = buf.toString("hex");
    console.log("token inside inside", token);
    return token;
  });

}
bzlight
  • 1,066
  • 4
  • 17
  • 43

1 Answers1

2

Easiest way of doing this is using sync way of randomBytes(), you can make it by just not providing a callback function:

function createResetToken() {
  return crypto.randomBytes(20).toString("hex");
}

By docs:

If a callback function is provided, the bytes are generated asynchronously and the callback function is invoked with two arguments: err and buf. If an error occurs, err will be an Error object; otherwise it is null. The buf argument is a Buffer containing the generated bytes.

...

If the callback function is not provided, the random bytes are generated synchronously and returned as a Buffer. An error will be thrown if there is a problem generating the bytes.

guijob
  • 4,413
  • 3
  • 20
  • 39
  • 1
    That works perfectly! Thanks for your help, especially so quickly! I'll accept your answer once it allows me to in 4 minutes – bzlight Aug 06 '19 at 05:37