How to append to a file in Node?

后端 未结 18 1262
庸人自扰
庸人自扰 2020-11-22 09:23

I am trying to append a string to a log file. However writeFile will erase the content each time before writing the string.

fs.writeFile(\'log.txt\'         


        
18条回答
  •  -上瘾入骨i
    2020-11-22 10:12

    My approach is rather special. I basically use the WriteStream solution but without actually 'closing' the fd by using stream.end(). Instead I use cork/uncork. This got the benefit of low RAM usage (if that matters to anyone) and I believe it's more safe to use for logging/recording (my original use case).

    Following is a pretty simple example. Notice I just added a pseudo for loop for showcase -- in production code I am waiting for websocket messages.

    var stream = fs.createWriteStream("log.txt", {flags:'a'});
    for(true) {
      stream.cork();
      stream.write("some content to log");
      process.nextTick(() => stream.uncork());
    }
    

    uncork will flush the data to the file in the next tick.

    In my scenario there are peaks of up to ~200 writes per second in various sizes. During night time however only a handful writes per minute are needed. The code is working super reliable even during peak times.

提交回复
热议问题