Search code examples
javascriptnode.jstokennode-crypto

Node crypto.randomBytes return token from function


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;
  });

}

Solution

  • 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.