How to append to a file in Node?

后端 未结 18 1229
庸人自扰
庸人自扰 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:22

    You need to open it, then write to it.

    var fs = require('fs'), str = 'string to append to file';
    fs.open('filepath', 'a', 666, function( e, id ) {
      fs.write( id, 'string to append to file', null, 'utf8', function(){
        fs.close(id, function(){
          console.log('file closed');
        });
      });
    });
    

    Here's a few links that will help explain the parameters

    open
    write
    close


    EDIT: This answer is no longer valid, look into the new fs.appendFile method for appending.

提交回复
热议问题