crypto.randomFillSync(buffer[, offset][, size])


  • buffer <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> 必须提供。所提供的 buffer 的大小不得大于 2**31 - 1。
  • offset <number> 起始位置,对于 TypedArray 是按元素计算,对于 ArrayBuffer 或 DataView 是按字节计算。默认值: 0
  • size <number> 要填充的数量,与 offset 使用相同的单位。默认值: 对于 TypedArray 为 buffer.length - offset,对于 ArrayBuffer 或 DataView 为 buffer.byteLength - offset。size 不能大于 2**31 - 1。
  • 返回:<ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> 作为 buffer 参数传递的对象。

crypto.randomFill() 的同步版本。

🌐 Synchronous version of crypto.randomFill().

import { Buffer } from 'node:buffer';
const { randomFillSync } = await import('node:crypto');

const buf = Buffer.alloc(10);
console.log(randomFillSync(buf).toString('hex'));

randomFillSync(buf, 5);
console.log(buf.toString('hex'));

// The above is equivalent to the following:
randomFillSync(buf, 5, 5);
console.log(buf.toString('hex'));const { randomFillSync } = require('node:crypto');
const { Buffer } = require('node:buffer');

const buf = Buffer.alloc(10);
console.log(randomFillSync(buf).toString('hex'));

randomFillSync(buf, 5);
console.log(buf.toString('hex'));

// The above is equivalent to the following:
randomFillSync(buf, 5, 5);
console.log(buf.toString('hex'));

任何 ArrayBuffer、TypedArray 或 DataView 实例都可以作为 buffer 传递。

🌐 Any ArrayBuffer, TypedArray or DataView instance may be passed as buffer.

import { Buffer } from 'node:buffer';
const { randomFillSync } = await import('node:crypto');

const a = new Uint32Array(10);
console.log(Buffer.from(randomFillSync(a).buffer,
                        a.byteOffset, a.byteLength).toString('hex'));

const b = new DataView(new ArrayBuffer(10));
console.log(Buffer.from(randomFillSync(b).buffer,
                        b.byteOffset, b.byteLength).toString('hex'));

const c = new ArrayBuffer(10);
console.log(Buffer.from(randomFillSync(c)).toString('hex'));const { randomFillSync } = require('node:crypto');
const { Buffer } = require('node:buffer');

const a = new Uint32Array(10);
console.log(Buffer.from(randomFillSync(a).buffer,
                        a.byteOffset, a.byteLength).toString('hex'));

const b = new DataView(new ArrayBuffer(10));
console.log(Buffer.from(randomFillSync(b).buffer,
                        b.byteOffset, b.byteLength).toString('hex'));

const c = new ArrayBuffer(10);
console.log(Buffer.from(randomFillSync(c)).toString('hex'));