What is random-bytes?
The 'random-bytes' npm package is used to generate cryptographically strong pseudo-random bytes. It is useful for creating secure tokens, unique identifiers, and other random data needed in various applications.
What are random-bytes's main functionalities?
Generate Random Bytes
This feature allows you to generate a specified number of random bytes. In this example, 16 random bytes are generated and converted to a hexadecimal string.
const randomBytes = require('random-bytes');
randomBytes(16, (err, buffer) => {
if (err) throw err;
console.log(buffer.toString('hex'));
});
Generate Random Bytes Synchronously
This feature allows you to generate random bytes synchronously. In this example, 16 random bytes are generated synchronously and converted to a hexadecimal string.
const randomBytes = require('random-bytes');
try {
const buffer = randomBytes.sync(16);
console.log(buffer.toString('hex'));
} catch (err) {
console.error(err);
}
Other packages similar to random-bytes
crypto
The 'crypto' module is a built-in Node.js module that provides cryptographic functionality, including a method to generate random bytes. It is more comprehensive than 'random-bytes' and includes various cryptographic operations such as hashing, encryption, and decryption.
uuid
The 'uuid' package is used to generate RFC-compliant UUIDs (Universally Unique Identifiers). While it does not generate random bytes directly, it uses random data to create unique identifiers, making it useful for similar purposes like generating unique tokens.
secure-random
The 'secure-random' package generates cryptographically strong random numbers and bytes. It offers similar functionality to 'random-bytes' but also includes additional features like generating random numbers within a specified range.
random-bytes

Generate strong pseudo-random bytes.
This module is a simple wrapper around the Node.js core crypto.randomBytes
API,
with the following additions:
- A
Promise
interface for environments with promises. - For Node.js versions that do not wait for the PRNG to be seeded, this module
will wait a bit.
Installation
$ npm install random-bytes
API
var randomBytes = require('random-bytes')
randomBytes(size, callback)
Generates strong pseudo-random bytes. The size
argument is a number indicating
the number of bytes to generate.
randomBytes(12, function (error, bytes) {
if (error) throw error
})
randomBytes(size)
Generates strong pseudo-random bytes and return a Promise
. The size
argument is
a number indicating the number of bytes to generate.
Note: To use promises in Node.js prior to 0.12, promises must be
"polyfilled" using global.Promise = require('bluebird')
.
randomBytes(18).then(function (string) {
})
randomBytes.sync(size)
A synchronous version of above.
var bytes = randomBytes.sync(18)
License
MIT