เมธอด crypto.randomFillSync() รับอาร์กิวเมนต์บัฟเฟอร์และคืนค่าบัฟเฟอร์ที่เติมด้วยค่าที่เข้ารหัสแล้ว ตามชื่อเมธอดนี้เป็นกระบวนการซิงโครนัส (synchronous)
ไวยากรณ์
crypto.randomFillSync(buffer, [offset], [size])
พารามิเตอร์
พารามิเตอร์ข้างต้นอธิบายดังนี้:
buffer – ฟิลด์นี้มีเนื้อหาข้อมูล ประเภทบัฟเฟอร์ที่เป็นไปได้: string, TypedArray, Buffer, ArrayBuffer, DataView ขนาดบัฟเฟอร์ไม่สามารถมากกว่า
2**31-1ได้offset – ค่าของออฟเซ็ตที่ randomFill จะเริ่มต้น ค่าเริ่มต้นคือ 0
size – ขนาดของบัฟเฟอร์หลังออฟเซ็ต คือ
(buffer.length - offset)ค่านี้ไม่สามารถมากกว่า2**31-1ได้
ตัวอย่าง
สร้างไฟล์ชื่อ randomFillSync.js และคัดลอกโค้ดด้านล่าง หลังจากสร้างไฟล์แล้ว ใช้คำสั่งต่อไปนี้เพื่อรันโค้ด:
node randomFillSync.js
randomFillSync.js
// ตัวอย่างการใช้ crypto.randomFillSync()
// นำเข้าโมดูล crypto
const crypto = require('crypto');
// กำหนดความยาวบัฟเฟอร์
const buffer = Buffer.alloc(15);
// บัฟเฟอร์
console.log(crypto.randomFillSync(buffer).toString('base64'));
// บัฟเฟอร์และออฟเซ็ต
crypto.randomFillSync(buffer, 4);
console.log(buffer.toString('base64'));
// บัฟเฟอร์, ออฟเซ็ต และขนาด
crypto.randomFillSync(buffer, 4, 4);
console.log(buffer.toString('base64'));
ผลลัพธ์
C:\home\node>> node randomFillSync.js wVBZ+i/nvmL3Ce4kBOl0 wVBZ+hkP5DB/4Ci8yTGs wVBZ+stVWJZ/4Ci8yTGs
ตัวอย่างเพิ่มเติม
ลองดูตัวอย่างอีกหนึ่งกรณี:
// ตัวอย่างการใช้ crypto.randomFillSync()
// นำเข้าโมดูล crypto
const crypto = require('crypto');
// สร้างอินสแตนซ์ TypedArray คือ Int8Array
const data = new Int8Array(16);
// บัฟเฟอร์, ออฟเซ็ต และขนาด
console.log(Buffer.from(crypto.randomFillSync(data).buffer, data.byteOffset, data.byteLength).toString('base64'));
console.log();
// สร้างอินสแตนซ์ TypedArray คือ BigInt64Array
const data2 = new BigInt64Array(4);
console.log(Buffer.from(crypto.randomFillSync(data2).buffer, data2.byteOffset, data2.byteLength).toString('ascii'));
console.log();
// สร้างอินสแตนซ์ DataView
const data3 = new DataView(new ArrayBuffer(7));
console.log(Buffer.from(crypto.randomFillSync(data3).buffer, data3.byteOffset, data3.byteLength).toString('hex'));
ผลลัพธ์
C:\home\node>> node randomFillSync.js iNm8tiwDATcV6I8xjTSTbQ== ra+I=(6&Xse"hjw?!EO?D#S7M d957fb1dbdfa00