Node.js crypto.randomBytes() Method
The crypto.randomBytes() method is used to generate a cryptographically well-built artificial random data and the number of bytes to be generated in the written code.
crypto.randomBytes( size, callback )
Parameters: This method accept 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.
Below example illustrate the use of crypto.randomBytes() method in Node.js:
Output: Here, callback function is provided so random bytes are generated synchronously.
The random data is: 074e48c8e3c0bc19f9e22dd7570037392e5d0bf80cf9dd51bb7808872a511b3
Output: Here, callback function is not provided so bytes are generated synchronously
The random bytes of data generated is: _??i???Z?Z?o?i?W??bEC ?F????#?-??T??jDqmm?v??7?Q?c_G?%?