How to append to a file in Node?

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

    In addition to denysonique's answer, sometimes asynchronous type of appendFile and other async methods in NodeJS are used where promise returns instead of callback passing. To do it you need to wrap the function with promisify HOF or import async functions from promises namespace:

    const { appendFile } = require('fs').promises;
    
    await appendFile('path/to/file/to/append', dataToAppend, optionalOptions);
    

    I hope it'll help

提交回复
热议问题