4

我知道诸如如何附加到节点中的文件之类的问题?

然而,那些不做我需要的。我所拥有的是一个在 nodejs 启动之前已经包含文本的文本文件,然后我希望节点在我的文件末尾附加文本。

但是,使用上面链接的问题中的方法会覆盖我的文件的内容。

我还发现我可以start:number在我的选项中使用,fs.createWriteStream所以如果我要弄清楚我的旧文件在哪里结束,我可以使用它来追加,但是我如何在不必读出整个文件并计算字符的情况下弄清楚这一点在里面?

4

2 回答 2

3

使用a+标志附加和创建一个文件(如果不存在)。

\r\n用作换行符。

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

文档:https ://nodejs.org/api/fs.html#fs_file_system_flags

于 2020-09-15T12:33:30.780 回答
2

I also found the documentation confusing, because it doesn't tell you how to actually set up that command (or that you may need to read in files before appending).

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);
于 2015-08-17T02:04:07.947 回答