crypto.randomFill() 메서드와 crypto.randomBytes() 메서드는 거의 동일합니다. 둘 사이의 유일한 차이점은 – randomFill() 메서드에서 첫 번째 인수는 채워질 버퍼입니다. 콜백이 구성된 경우에만 오류가 발생했을 때 호출되는 콜백 메서드도 있습니다.
구문
crypto.randomFill(buffer, [offset], [size], [callback])
매개변수
위의 매개변수는 다음과 같이 설명됩니다. -
-
버퍼 – 이 필드는 데이터 내용을 포함합니다. 가능한 버퍼 유형은 string, TypedArray, Buffer, ArrayBuffer, DataView입니다. 버퍼의 크기는 2**31-1보다 클 수 없습니다.
-
오프셋 – randomFill이 시작되는 오프셋 값. 기본값은 0입니다.
-
크기 – 오프셋 이후의 버퍼 크기. 즉 (buffer.length-offset). 이 값은 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'));
}); 인코딩으로 randomFill 데이터 인쇄 출력
C:\home\node>> node randomFill.js >h(Be#D8h0