Generates cryptographically strong pseudorandom data. The size argument
is a number indicating the number of bytes to generate.
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. Thebuf argument is a Buffer containing the generated bytes.
randomBytes(256, (err, buf) => { if (err) throwerr; console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`); });
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.
constbuf = randomBytes(256); console.log( `${buf.length} bytes of random data: ${buf.toString('hex')}`);
The crypto.randomBytes() method will not complete until there is
sufficient entropy available.
This should normally never take longer than a few milliseconds. The only time
when generating the random bytes may conceivably block for a longer period of
time is right after boot, when the whole system is still low on entropy.
This API uses libuv's threadpool, which can have surprising and
negative performance implications for some applications; see the UV_THREADPOOL_SIZE documentation for more information.
The asynchronous version of crypto.randomBytes() is carried out in a single
threadpool request. To minimize threadpool task length variation, partition
large randomBytes requests when doing so as part of fulfilling a client
request.
since
v0.5.8
Parameters
size: number
The number of bytes to generate. The size must not be larger than 2**31 - 1.
Generates cryptographically strong pseudorandom data. The
size
argument is a number indicating the number of bytes to generate.If a
callback
function is provided, the bytes are generated asynchronously and thecallback
function is invoked with two arguments:err
andbuf
. If an error occurs,err
will be anError
object; otherwise it isnull
. Thebuf
argument is aBuffer
containing the generated bytes.If the
callback
function is not provided, the random bytes are generated synchronously and returned as aBuffer
. An error will be thrown if there is a problem generating the bytes.The
crypto.randomBytes()
method will not complete until there is sufficient entropy available. This should normally never take longer than a few milliseconds. The only time when generating the random bytes may conceivably block for a longer period of time is right after boot, when the whole system is still low on entropy.This API uses libuv's threadpool, which can have surprising and negative performance implications for some applications; see the
UV_THREADPOOL_SIZE
documentation for more information.The asynchronous version of
crypto.randomBytes()
is carried out in a single threadpool request. To minimize threadpool task length variation, partition largerandomBytes
requests when doing so as part of fulfilling a client request.v0.5.8