poseid
poseid

Reputation: 7156

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

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

Upvotes: 4

Views: 49053

Answers (5)

9me
9me

Reputation: 1138

If you are using ES6 then its also easy

String.fromCharCode(...bytes)
Promise.resolve(String.fromCharCode(...bytes)) // Promise

or

String.fromCharCode.apply(null, bytes)
Promise.resolve(String.fromCharCode.apply(null, bytes)) // Promise

Upvotes: 2

Esailija
Esailija

Reputation: 140220

You can just use crypto that comes with node:

var Promise = require("bluebird");
var crypto = Promise.promisifyAll(require("crypto"));

crypto.randomBytesAsync(20).then(function(bytes){
    console.log('random byte string:', bytes.toString("hex"));
});

Logs:

random byte string: 39efc98a75c87fd8d5172bbb1f291de1c6064849

Upvotes: 4

Andrew
Andrew

Reputation: 5340

Try this:

new Buffer(bytes).toString('ascii');

More details here: http://nodejs.org/api/buffer.html

Upvotes: 31

robertklep
robertklep

Reputation: 203286

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

Upvotes: 2

Ginden
Ginden

Reputation: 5317

Do you want to conver it to ASCII? If not, this is my code (1 minute of work):

  var z;
 randomSource.getRandomBytes(20, function(){z=arguments[0]})
 z
<Buffer c8 64 03 d1 2d 27 7d 8e 8f 14 ec 48 e2 97 46 84 5a d7 c7 2f>
 String(z)
'�d\u0003�-\'}��\u0014�H��F�Z��/'

Upvotes: 0

Related Questions