How to append to a file in Node?

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

    Use a+ flag to append and create a file (if doesn't exist):

    fs.writeFile('log.txt', 'Hello Node', { flag: "a+" }, (err) => {
      if (err) throw err;
      console.log('The file is created if not existing!!');
    }); 
    

    Docs: https://nodejs.org/api/fs.html#fs_file_system_flags

提交回复
热议问题