【问题标题】:How to write large random binary file with NodeJS如何使用 NodeJS 编写大型随机二进制文件
【发布时间】:2019-11-24 06:31:59
【问题描述】:

想使用 NodeJS 将大型二进制文件写入磁盘,但 WriteStream.write 是异步的并且在写入文件之前关闭,导致文件为空。

【问题讨论】:

    标签: node.js file binary fs


    【解决方案1】:

    这就是我要做的工作。

    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);
    

    【讨论】:

      猜你喜欢
      • 2015-11-29
      • 1970-01-01
      • 2016-09-20
      • 2011-07-31
      • 2018-01-29
      • 1970-01-01
      • 1970-01-01
      • 2012-02-12
      • 2010-12-02
      相关资源
      最近更新 更多