除了内存问题之外,您还会遇到加密模块的问题,因为它可以生成的字节数是有限的。
您将需要使用fs.createWriteStream以块的形式生成和写入数据,而不是一次性生成。
以下是Node 文档中关于流的一些代码的修改版本,用于将随机字节块流式传输到文件:
const fs = require("fs");
const crypto = require('crypto');
const fileName = "random-bytes.bin";
const fileSizeInBytes = Number.parseInt(process.argv[2]) || 1000;
console.log(`Writing ${fileSizeInBytes} bytes`)
const writer = fs.createWriteStream(fileName)
writetoStream(fileSizeInBytes, () => console.log(`File created: ${fileName}`));
function writetoStream(bytesToWrite, callback) {
const step = 1000;
let i = bytesToWrite;
write();
function write() {
let ok = true;
do {
const chunkSize = i > step ? step : i;
const buffer = crypto.randomBytes(chunkSize);
i -= chunkSize;
if (i === 0) {
// Last time!
writer.write(buffer, callback);
} else {
// See if we should continue, or wait.
// Don't pass the callback, because we're not done yet.
ok = writer.write(buffer);
}
} while (i > 0 && ok);
if (i > 0) {
// Had to stop early!
// Write some more once it drains.
writer.once('drain', write);
}
}
}
还有一些在线工具可让您以较少的设置生成所需大小的文件。这些文件也在您的系统上生成,因此不必通过网络下载它们。