How to append to a file in Node?

后端 未结 18 1216
庸人自扰
庸人自扰 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条回答
  •  隐瞒了意图╮
    2020-11-22 10:17

    I offer this suggestion only because control over open flags is sometimes useful, for example, you may want to truncate it an existing file first and then append a series of writes to it - in which case use the 'w' flag when opening the file and don't close it until all the writes are done. Of course appendFile may be what you're after :-)

      fs.open('log.txt', 'a', function(err, log) {
        if (err) throw err;
        fs.writeFile(log, 'Hello Node', function (err) {
          if (err) throw err;
          fs.close(log, function(err) {
            if (err) throw err;
            console.log('It\'s saved!');
          });
        });
      });
    

提交回复
热议问题