ทั้งวิธี crypto.randomFill() และ crypto.randomBytes() เกือบจะเหมือนกัน ข้อแตกต่างระหว่างทั้งสองคือ – ในวิธี randomFill() อาร์กิวเมนต์แรกคือบัฟเฟอร์ที่จะเติม นอกจากนี้ยังมีวิธีการโทรกลับที่เรียกใช้เมื่อพบข้อผิดพลาดเฉพาะเมื่อมีการกำหนดค่าการโทรกลับเท่านั้น
ไวยากรณ์
crypto.randomFill(buffer, [offset], [size], [callback])
พารามิเตอร์
พารามิเตอร์ข้างต้นอธิบายไว้ด้านล่าง −
-
บัฟเฟอร์ – ช่องนี้มีเนื้อหาข้อมูล ประเภทบัฟเฟอร์ที่เป็นไปได้คือ:string, TypedArray, Buffer, ArrayBuffer, DataView ขนาดของบัฟเฟอร์ต้องไม่เกิน 2**31-1
-
ออฟเซ็ต – ค่าออฟเซ็ตจากจุดเริ่มต้นของการเติมแบบสุ่ม ค่าเริ่มต้นคือ 0
-
ขนาด – ขนาดของบัฟเฟอร์หลังออฟเซ็ต เช่น (บัฟเฟอร์.ความยาว-ออฟเซ็ต). ค่านี้ต้องไม่มากกว่า 2**31-1
-
โทรกลับ – ฟังก์ชั่นที่จะเรียกเมื่อมีข้อผิดพลาดเกิดขึ้น
ตัวอย่าง
สร้างไฟล์ที่มีชื่อ – randomFill.js และคัดลอกข้อมูลโค้ดด้านล่าง หลังจากสร้างไฟล์แล้ว ให้ใช้คำสั่งต่อไปนี้เพื่อเรียกใช้โค้ดนี้ดังแสดงในตัวอย่างด้านล่าง −
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'));
}); ผลลัพธ์
C:\home\node>> node randomFill.js f!]"+– ZqHdoit8 ZqHdoit8
ตัวอย่าง
ลองดูอีกตัวอย่างหนึ่ง
// 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'));
}); ผลลัพธ์
C:\home\node>> node randomFill.js >h(Be#D8h0