How to convert an array of bytes into string with Node.js?

javascript, node.js

Solution

`randbytes` works asynchronously. If you want to combine it with promises, you need to use a Promises-lib as well. I'm using `when` as an example:

var when          = require('when');
var RandBytes     = require('randbytes');
var randomSource  = RandBytes.urandom.getInstance();

function get_rand() {
  var dfd = when.defer();
  randomSource.getRandomBytes(20, function(bytes) {
    dfd.resolve( bytes.toString('hex') ); // convert to hex string
  });
  return dfd.promise;
}

// example call:
get_rand().then(function(bytes) {
  console.log('random byte string:', bytes);
});

Problem

I need a random sequence of bytes for making a password hash. In Ruby, this would look like: ``` File.open("/dev/urandom").read(20).each_byte{|x| rand << sprintf("%02x",x)} ``` In Node.js, I can get a sequence of random bytes with: ``` var randomSource = RandBytes.urandom.getInstance(); var bytes = randomSource.getRandomBytesAsync(20); ``` But the problem is, how to convert these to a String? Also, I need to have them wrapped in promisses. Would this work: ``` get_rand() .then(function(bytes) { authToken = bytes; }) ```

Original source