Node.js 中的 crypto.randomFill() 方法

node.jsjavascriptweb developmentfront end technology

crypto.randomFill() 方法和 crypto.randomBytes() 方法几乎相同。两者之间的唯一区别是 – 在 randomFill() 方法中,第一个参数是将被填充的缓冲区。它还有一个回调方法,只有在配置了回调的情况下,才会在遇到错误时调用该方法。

语法

crypto.randomFill(buffer, [offset], [size], [callback])

参数

上述参数描述如下 −

  • buffer – 此字段包含数据内容。可能的缓冲区类型为:string、TypedArray、Buffer、ArrayBuffer、DataView。缓冲区的大小不能大于 2**31-1。

  • offset ——randomFill 开始的偏移量值。默认值为 0。

  • size ——偏移后的缓冲区大小。即 (buffer.length-offset)。此值不能大于 2**31-1。

  • callback ——抛出错误时将调用的函数。

示例

创建一个名为 – randomFill.js 的文件并复制以下代码片段。创建文件后,使用以下命令运行此代码,如下例所示 −

node randomFill.js

randomFill.js

// Node.js 程序演示 crypto.randomFill() 方法的流程

// 导入 crypto 模块
const crypto = require('crypto');
const fs = require("fs");

// 初始化缓冲区字节值
const buf = Buffer.alloc(6);

// 使用缓冲区和回调调用 randomFill 方法
crypto.randomFill(buf, (err, buf) => {
   if (err) throw err;
   // 填充后打印缓冲区数据值
   console.log(buf.toString('ascii'));
});

//使用上面定义的所有参数调用 randomFill
crypto.randomFill(buf, 3, 2, (err, buf) => {
   if (err) throw err;
   // 在缓冲区中打印新的随机数据
   console.log(buf.toString('base64'));
});

// 我们可以看到,下面的函数的输出相同
crypto.randomFill(buf, 3, 3, (err, buf) => {
   if (err) throw err;
   console.log(buf.toString('base64'));
});

输出

C:\home
ode>> node randomFill.js f!]"+– ZqHdoit8 ZqHdoit8

示例

我们再看一个例子。

// Node.js 程序演示 crypto.randomFill() 方法的流程

// 导入 crypto 模块
const crypto = require('crypto');
const fs = require("fs");

// 使用数据视图初始化缓冲区字节值
const data = new DataView(new ArrayBuffer(16));

// 使用缓冲区和回调调用 randomFill 方法
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
ode>> node randomFill.js >h(Be#D8h0

相关文章