想使用NodeJS将大型二进制文件写入磁盘,但WriteStream.write是异步的,并且在写入文件之前关闭,从而导致文件为空。
答案 0 :(得分:0)
这就是我要工作的。
var crypto = require('crypto');
var fs = require('fs');
function writeFile(i) {
const fileKey = Math.floor(Math.random()*2000*1000*500);
var wstream = fs.createWriteStream(`myBinaryFile${fileKey}.dat`);
// create another Buffer of 100 bytes and write
const fileSize = Math.floor(Math.random()*2000*1000*500);
console.log(`Writing ${Math.floor(fileSize/1000/1000)} MB to file ${i} with id ${fileKey}`)
wstream.write(crypto.randomBytes(fileSize));
wstream.end();
wstream.on("finish", function() {
setTimeout(() => {
writeFile(i+1)
}, 15000);
});
}
writeFile(0);
setInterval(() => {}, 1000);