Node crypto.randomBytes() Method

The crypto.randomBytes() method is used to generate cryptographically well-built artificial random data and the number of bytes to be generated in the written code.

Syntax: 

crypto.randomBytes( size, callback )

Parameters: This method accepts two parameters as mentioned above and described below:  

  • size: It is of type number which indicates the number of bytes to be generated.
  • callback: It is a function which is made of two parameters namely, err and buf. However, if a callback function is available in the stated code then the bytes are generated asynchronously else these bytes are generated synchronously.

Return Type: It returns a Buffer if the callback function is given.

Example 1: Below example illustrate the use of crypto.randomBytes() method in Node.js:

Javascript




// Node.js program to demonstrate the
// crypto.randomBytes() method
 
// Including crypto module
const crypto = require('crypto');
 
// Calling randomBytes method with callback
crypto.randomBytes(127, (err, buf) => {
    if (err) {
        // Prints error
        console.log(err);
        return;
    }
 
    // Prints random bytes of generated data
    console.log("The random data is: "
        + buf.toString('hex'));
});


Output: Here, callback function is provided so random bytes are generated asynchronously. 

The random data is:

074e48c8e3c0bc19f9e22dd7570037392e5d0bf80cf9dd51bb7808872a511b3 c1cd91053fca873a4cb7b2549ec1010a9a1a4c2a6aceead9d115eb9d60a1630e056f3accb10574cd563 371296d4e4e898941231d06d8dd5de35690c4ba94ca12729aa316365145f8a00c410a859c40a46bbb4d 5d51995241eec8f6b7a90415e

Example 2: Below examples illustrate the use of crypto.randomBytes() Method in Node.js:

Javascript




// Node.js program to demonstrate the
// crypto.randomBytes() method
 
// Including crypto module
const crypto = require('crypto');
 
// Calling randomBytes method without callback
const buf = crypto.randomBytes(60);
 
// Prints random bytes of generated data
console.log("The random bytes of data generated is: "
    + buf.toString('hex'));


Output: Here, callback function is not provided so bytes are generated synchronously 

The random bytes of data generated is: 865f38a9950699794e81fcd91584f8612f5a42aec5b7bbed48c1683832c519c22c836c91fe1afc0330a2ea02dea0a31a1f509dfde1a780ce82ec0eb1

We have a Cheat Sheet on Node crypto methods where we covered all the crypto methods to check those please go through Crypto Module Complete Reference this article.