首页 文章

如何附加到Node中的文件?

提问于
浏览
366

我试图将一个字符串附加到日志文件 . 但是,writeFile会在每次写入字符串之前擦除内容 .

fs.writeFile('log.txt', 'Hello Node', function (err) {
  if (err) throw err;
  console.log('It\'s saved!');
}); // => message.txt erased, contains only 'Hello Node'

知道怎么做这个简单的方法吗?

丹尼尔

12 回答

  • 19

    节点0.8有 fs.appendFile

    fs.appendFile('message.txt', 'data to append', function (err) {
      if (err) throw err;
      console.log('The "data to append" was appended to file!');
    });
    

    文件:http://nodejs.org/docs/latest/api/fs.html#fs_fs_appendfile_filename_data_encoding_utf8_callback

  • 575

    使用jfile包:

    myFile.text+='\nThis is new line to be appended'; //myFile=new JFile(path);
    
  • 0

    更简单的方法是

    const fs = require('fs');
    fs.appendFileSync('file.txt', 'message to append into file');
    
  • 1

    这里's a full script. Fill in your file names and run it and it should work! Here'是一个关于脚本背后逻辑的video tutorial .

    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);
    
  • 13

    你需要打开它,然后写入它 .

    var fs = require('fs'), str = 'string to append to file';
    fs.open('filepath', 'a', 666, function( e, id ) {
      fs.write( id, 'string to append to file', null, 'utf8', function(){
        fs.close(id, function(){
          console.log('file closed');
        });
      });
    });
    

    以下是一些有助于解释参数的链接

    open
    write
    close


    EDIT :此答案不再有效,请查看新的fs.appendFile方法进行追加 .

  • 103

    对于偶尔的追加,您可以使用 appendFile ,每次调用时都会创建一个新的文件句柄:

    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');
    

    但是如果你反复追加到同一个文件,那么reuse the file handle要好得多 .

  • 3

    除了 appendFile 之外,您还可以在 writeFile 中传递一个标志,以将数据附加到现有文件 .

    fs.writeFile('log.txt', 'Hello Node',  {'flag':'a'},  function(err) {
        if (err) {
            return console.error(err);
        }
    });
    

    通过传递标记'a',数据将附加在文件的末尾 .

  • 1

    如果你想要一个简单,无压力的方法在文件中逐行写日志,那么我建议fs-extra

    const os = require('os');
    const fs = require('fs-extra');
    
    const file = 'logfile.txt';
    const options = {flag: 'a'};
    
    async function writeToFile(text) {
      await fs.outputFile(file, `${text}${os.EOL}`, options);
    }
    
    writeToFile('First line');
    writeToFile('Second line');
    writeToFile('Third line');
    writeToFile('Fourth line');
    writeToFile('Fifth line');
    

    使用Node v8.9.4进行测试 .

  • 103

    如果要在日志文件中写入,即将数据附加到文件末尾, never 使用 appendFileappendFile 会为您添加到文件中的每个数据打开文件句柄,过一会儿就会出现漂亮的_395902错误 .

    我可以补充说 appendFile 并不比 WriteStream 更容易使用 .

    appendFile 示例:

    console.log(new Date().toISOString());
    [...Array(10000)].forEach( function (item,index) {
        fs.appendFile("append.txt", index+ "\n", function (err) {
            if (err) console.log(err);
        });
    });
    console.log(new Date().toISOString());
    

    在我的计算机上最多8000个,你可以将数据附加到文件,然后你得到这个:

    { Error: EMFILE: too many open files, open 'C:\mypath\append.txt'
        at Error (native)
      errno: -4066,
      code: 'EMFILE',
      syscall: 'open',
      path: 'C:\\mypath\\append.txt' }
    

    此外, appendFile 将在启用时写入,因此您的日志将不会被时间戳写入 . 你可以用例子测试,设置1000代替100000,命令会随机,取决于访问文件 .

    如果要附加到文件, must 使用这样的可写流:

    var stream = fs.createWriteStream("append.txt", {flags:'a'});
    console.log(new Date().toISOString());
    [...Array(10000)].forEach( function (item,index) {
        stream.write(index + "\n");
    });
    console.log(new Date().toISOString());
    stream.end();
    

    你想要的时候结束它 . 您甚至不需要使用 stream.end() ,默认选项是 AutoClose:true ,因此您的文件将在您的流程结束时结束并且您避免打开太多文件 .

  • 17
    fd = fs.openSync(path.join(process.cwd(), 'log.txt'), 'a')
    fs.writeSync(fd, 'contents to append')
    fs.closeSync(fd)
    
  • 2

    我提供这个建议只是因为控制打开标志有时很有用,例如,您可能希望先将其截断为现有文件,然后向其附加一系列写入 - 在这种情况下,在打开文件时使用'w'标志并且不要't close it until all the writes are done. Of course appendFile may be what you'重新:-)

    fs.open('log.txt', 'a', function(err, log) {
        if (err) throw err;
        fs.writeFile(log, 'Hello Node', function (err) {
          if (err) throw err;
          fs.close(log, function(err) {
            if (err) throw err;
            console.log('It\'s saved!');
          });
        });
      });
    
  • 1

    使用createWriteStream的代码为每次写入创建文件描述符 . log.end更好,因为它要求节点在写入后立即关闭 .

    var fs = require('fs');
    var logStream = fs.createWriteStream('log.txt', {'flags': 'a'});
    // use {'flags': 'a'} to append and {'flags': 'w'} to erase and write a new file
    logStream.write('Initial line...');
    logStream.end('this is the end line');
    

相关问题