How to append to a file in Node?

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

    For occasional appends, you can use appendFile, which creates a new file handle each time it's called:

    Asynchronously:

    const fs = require('fs');
    
    fs.appendFile('message.txt', 'data to append', function (err) {
      if (err) throw err;
      console.log('Saved!');
    });
    

    Synchronously:

    const fs = require('fs');
    
    fs.appendFileSync('message.txt', 'data to append');
    

    But if you append repeatedly to the same file, it's much better to reuse the file handle.

提交回复
热议问题