为什么此Node stream.write不会覆盖文件内容?性能如何随Node fwrite改变?

时间:2019-07-04 05:28:49

标签: javascript node.js fs node-streams

我的意图是为特定间隔写入文件。在时间间隔之外创建了一个节点writeStream,并尝试使用时间间隔内的同一流将内容写入文件中。我希望内容会被覆盖,但是已经开始追加。这是一种方法

方法I:

var fs = require('fs');
var ans = ["first","second","third","fourth","fifth"];
var i =0;
var stream = fs.createWriteStream('stats.log.info',{flags:'w'});
var writeInterval = setInterval(function(){
  var data =ans[i%ans.length] ;
  if(data.length == 0){
    console.log("Failure in ");
  }
  stream.on('error', function(err){
    console.log("error in creating a stream "+err);
    clearInterval(writeInterval);
    stream.destroy();
    return;
  });
  stream.write(data);

  i++;
},2000);

然后,我将创建的流移动到间隔内,最终覆盖了文件内容。 方法I:创建了放置在间隔内的流

var fs = require('fs');
var ans = ["first","second","third","fourth","fifth"];
var i =0;
var writeInterval = setInterval(function(){
  var stream = fs.createWriteStream('stats.log.info',{flags:'w'});

  var data =ans[i%ans.length] ;
      if(data.length == 0){
        console.log("Failure in ");
      }
      stream.on('error', function(err){
        console.log("error in creating a stream "+err);
        clearInterval(writeInterval);
        stream.destroy();
        return;
      });
      stream.write(data);

      i++;
    },2000);

我想知道如何使用一个创建的流来覆盖文件内容。我尝试了使用Node标准文件写入的另一种方法。它可以完美地覆盖内容。但是它在时间间隔内包含了fopen和fclose,每次操作似乎都非常昂贵。这是示例

方法II:

var fs = require('fs');
var ans = ["first","second","third","fourth","fifth"];
var i =0;
var writeInterval = setInterval(function(){
  var data =ans[i%ans.length] ;
  if(data.length == 0){
    console.log("Failure in ");
  }
    var fopen_write = fs.open("curr.log", 'w', function(err, fd){
        var buf = new Buffer(data, 'utf8');
        fs.write(fd, buf, 0, buf.length, null, function(err) {
            if (err) throw 'error writing file: ' + err;
            fs.close(fd, function() {
                console.log('wrote the file successfully');
            });
        });
    })
  i++;
},2000);

关于如何评估性能更好的方法的建议确实很有帮助。

感谢您的辛勤工作!

1 个答案:

答案 0 :(得分:0)

尝试

var fs = require('fs');
var ans = ["first","second","third","fourth","fifth"];
var i =0;
var stream = fs.createWriteStream('stats.log.info',{flags:'w'});
var writeInterval = setInterval(function(){
  var data =ans[i%ans.length] ;
  if(data.length == 0){
    console.log("Failure in ");
  }
  stream.on('error', function(err){
    console.log("error in creating a stream "+err);
    clearInterval(writeInterval);
    stream.destroy();
    return;
  });
  stream.pos = 0;// set pos to 0;
  stream.write(data);
  i++;
},2000);

但是,这是一个坏主意! pos不是writeStream的标准属性,并且继续调用文件写入流的write方法意味着将数据追加到文件中,我们最好不要更改此行为。