How to append to a file in Node?

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

    Using fs.appendFile or fsPromises.appendFile are the fastest and the most robust options when you need to append something to a file.

    In contrast to some of the answers suggested, if the file path is supplied to the appendFile function, It actually closes by itself. Only when you pass in a filehandle that you get by something like fs.open() you have to take care of closing it.

    I tried it with over 50,000 lines in a file.

    Examples :

    (async () => {
      // using appendFile.
      const fsp = require('fs').promises;
      await fsp.appendFile(
        '/path/to/file', '\r\nHello world.'
      );
    
      // using apickfs; handles error and edge cases better.
      const apickFileStorage = require('apickfs');
      await apickFileStorage.writeLines(
        '/path/to/directory/', 'filename', 'Hello world.'
      );
    })();
    

    Ref: https://github.com/nodejs/node/issues/7560
    Example Execution: https://github.com/apickjs/apickFS/blob/master/writeLines.js

提交回复
热议问题