crypto.randomFill() Method in Node.js

Node.jsJavascriptWeb DevelopmentFront End Technology

Both the crypto.randomFill() method and crypto.randomBytes() method are almost same. The only difference between the two is that – In randomFill() method the first argument is a buffer that will be filled. It also has a callback method that is called when an error is encountered only if the callback is configured.

Syntax

crypto.randomFill(buffer, [offset], [size], [callback])

Parameters

The above parameters are described as below −

  • buffer – This field contains the data content. Possible buffer types are: string, TypedArray, Buffer, ArrayBuffer, DataView. The size of the buffer cannot be greater than 2**31-1.

  • offset – The value of the offset from where randomFill will start. Default value is 0.

  • size – The size of the buffer after the offset. i.e. (buffer.length-offset). This value cannot be greater than 2**31-1.

  • callback – The function which will be called when an error is thrown.

Example

Create a file with name – randomFill.js and copy the below code snippet. After creating file, use the following command to run this code as shown in the example below −

node randomFill.js

randomFill.js

// Node.js program to demonstrate the flow of crypto.randomFill() method

// Importing the crypto module
const crypto = require('crypto');
const fs = require("fs");

// Initialising the buffer bytes value
const buf = Buffer.alloc(6);

// Calling the randomFill method with buffer and a callback
crypto.randomFill(buf, (err, buf) => {
   if (err) throw err;
   // Printing the buffer data value after filling
   console.log(buf.toString('ascii'));
});

//Calling the randomFill with all the parameters defined above
crypto.randomFill(buf, 3, 2, (err, buf) => {
   if (err) throw err;
   // Printing the new random data in buffer
   console.log(buf.toString('base64'));
});

// We can see that the output will be same for below function
crypto.randomFill(buf, 3, 3, (err, buf) => {
   if (err) throw err;
   console.log(buf.toString('base64'));
});

Output

C:\home\node>> node randomFill.js
f!]"+–
ZqHdoit8
ZqHdoit8

Example

Let's take a look at one more example.

// Node.js program to demonstrate the flow of crypto.randomFill() method

// Importing the crypto module
const crypto = require('crypto');
const fs = require("fs");

// Initialising the buffer bytes value using data view
const data = new DataView(new ArrayBuffer(16));

// Calling the randomFill method with buffer and a callback
crypto.randomFill(data, (err, buf) => {
   if (err) throw err;
   // Printing the randomFill data with encoding
   console.log(Buffer.from(buf.buffer,
      buf.byteOffset, buf.byteLength).toString('ascii'));
});

Output

C:\home\node>> node randomFill.js
>h(Be#D8h0
raja
Published on 20-May-2021 12:55:23
Advertisements