Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
crypto.randomFill() Method in Node.js
The crypto.randomFill() method in Node.js fills an existing buffer with cryptographically strong random data. Unlike crypto.randomBytes() which creates a new buffer, randomFill() fills a provided buffer with random data.
Syntax
crypto.randomFill(buffer, [offset], [size], [callback])
Parameters
buffer - The buffer to be filled. Supported types: Buffer, TypedArray, ArrayBuffer, DataView. Maximum size is 2**31-1.
offset - Starting position for filling (optional). Default is 0.
size - Number of bytes to fill from the offset (optional). Default is buffer.length - offset.
callback - Function called when operation completes or errors occur (optional).
Example: Basic randomFill() Usage
const crypto = require('crypto');
// Create a buffer of 6 bytes
const buf = Buffer.alloc(6);
// Fill entire buffer with random data
crypto.randomFill(buf, (err, filledBuf) => {
if (err) throw err;
console.log('Random buffer (hex):', filledBuf.toString('hex'));
console.log('Random buffer (base64):', filledBuf.toString('base64'));
});
Random buffer (hex): a3f2c1d4e8b7 Random buffer (base64): o/LB1Oi3
Example: Using Offset and Size Parameters
const crypto = require('crypto');
const buf = Buffer.alloc(8);
console.log('Original buffer:', buf.toString('hex'));
// Fill 3 bytes starting from offset 2
crypto.randomFill(buf, 2, 3, (err, filledBuf) => {
if (err) throw err;
console.log('After randomFill:', filledBuf.toString('hex'));
});
Original buffer: 0000000000000000 After randomFill: 0000f3a2c1000000
Example: Using with DataView
const crypto = require('crypto');
// Create DataView from ArrayBuffer
const dataView = new DataView(new ArrayBuffer(12));
crypto.randomFill(dataView, (err, filledData) => {
if (err) throw err;
// Convert to Buffer for easier display
const buffer = Buffer.from(filledData.buffer,
filledData.byteOffset, filledData.byteLength);
console.log('DataView filled with random data:', buffer.toString('hex'));
});
DataView filled with random data: d4f8a2c1b5e7f3d2a8c4
Synchronous vs Asynchronous
| Method | Operation | Usage |
|---|---|---|
randomFill(buffer, callback) |
Asynchronous | Non-blocking, preferred for applications |
randomFillSync(buffer) |
Synchronous | Blocking, use only when necessary |
Key Points
- Modifies the original buffer in-place
- Provides cryptographically secure random data
- Maximum buffer size is 2**31-1 bytes
- Callback receives (error, buffer) parameters
- Works with various buffer types including TypedArray and DataView
Conclusion
The crypto.randomFill() method efficiently fills existing buffers with secure random data. Use it when you need to populate pre-allocated buffers rather than creating new ones with randomBytes().
