How to append to a file in Node?

后端 未结 18 1261
庸人自扰
庸人自扰 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条回答
  •  -上瘾入骨i
    2020-11-22 10:20

    Here's a full script. Fill in your file names and run it and it should work! Here's a video tutorial on the logic behind the script.

    var fs = require('fs');
    
    function ReadAppend(file, appendFile){
      fs.readFile(appendFile, function (err, data) {
        if (err) throw err;
        console.log('File was read');
    
        fs.appendFile(file, data, function (err) {
          if (err) throw err;
          console.log('The "data to append" was appended to file!');
    
        });
      });
    }
    // edit this with your file names
    file = 'name_of_main_file.csv';
    appendFile = 'name_of_second_file_to_combine.csv';
    ReadAppend(file, appendFile);
    

提交回复
热议问题