Cả crypto.randomFill() và crypto.randomBytes() gần như giống nhau. Khác biệt: randomFill() nhận buffer làm tham số đầu tiên để điền, và có callback được gọi khi gặp lỗi (nếu callback được cấu hình).
Cú pháp
crypto.randomFill(buffer, [offset], [size], [callback])
Tham số
buffer – Chứa dữ liệu. Kiểu: string, TypedArray, Buffer, ArrayBuffer, DataView. Kích thước ≤ 2**31-1.
offset – Vị trí bắt đầu. Mặc định: 0.
size – Kích thước sau offset (
buffer.length - offset). ≤ 2**31-1.callback – Hàm gọi khi có lỗi.
Ví dụ
Tạo file randomFill.js và sao chép mã. Chạy lệnh:
node randomFill.js
randomFill.js
// Chương trình Node.js minh họa crypto.randomFill()
// Import module crypto
const crypto = require('crypto');
const fs = require("fs");
// Khởi tạo buffer 6 byte
const buf = Buffer.alloc(6);
// Gọi randomFill với buffer và callback
crypto.randomFill(buf, (err, buf) => {
if (err) throw err;
// In buffer sau khi điền
console.log(buf.toString('ascii'));
});
// Gọi randomFill với tất cả tham số
crypto.randomFill(buf, 3, 2, (err, buf) => {
if (err) throw err;
console.log(buf.toString('base64'));
});
// Kết quả giống nhau cho hàm dưới
crypto.randomFill(buf, 3, 3, (err, buf) => {
if (err) throw err;
console.log(buf.toString('base64'));
});
Kết quả
C:\home\node>> node randomFill.js f!"]+– ZqHdoit8 ZqHdoit8
Ví dụ 2
Ví dụ với DataView.
// Chương trình Node.js minh họa crypto.randomFill()
// Import module crypto
const crypto = require('crypto');
const fs = require("fs");
// Khởi tạo buffer bằng DataView
const data = new DataView(new ArrayBuffer(16));
// Gọi randomFill với callback
crypto.randomFill(data, (err, buf) => {
if (err) throw err;
// In dữ liệu randomFill với mã hóa
console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength).toString('ascii'));
});
Kết quả
C:\home\node>> node randomFill.js >h(Be#D8h0