如何附加到节点中的文件?

时间:2022-04-12 03:25:14

I am trying to append a string to a log file. However writeFile will erase the content each time before writing the string.

我试图将字符串附加到日志文件中。然而,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'

Any idea how to do this the easy way?

你知道怎么用简单的方法来做吗?

Daniel

丹尼尔

12 个解决方案

#1


519  

For occasional appends, you can use appendFile, which creates a new file handle each time it's called:

对于偶尔的附加文件,您可以使用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');

But if you append repeatedly to the same file, it's much better to reuse the file handle.

但是如果您重复地向同一个文件追加,那么最好重用文件句柄。

#2


96  

Your code using createWriteStream creates a file descriptor for every write. log.end is better because it asks node to close immediatelly after the write.

使用createWriteStream的代码为每次写入创建一个文件描述符。日志。结尾更好,因为它要求节点在写完后立即关闭。

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

#3


64  

When you want to write in a log file, i.e. appending data to the end of a file, never uses appendFile, appendFile opens a file handle for each piece of data you add to your file, after a while you get a beautiful EMFILE error.

当您想要在一个日志文件中写入时,也就是将数据附加到文件的末尾,不要使用appendFile, appendFile会为您添加到文件中的每一个数据打开一个文件句柄,稍后您会得到一个漂亮的EMFILE错误。

I can add that appendFile is not easier to use than a WriteStream.

我可以添加appendFile并不比WriteStream更容易使用。

Example with appendFile:

与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());

Up to 8000 on my computer, you can append data to the file, then you obtain this:

在我的电脑上最多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' }

Moreover, appendFile will write when it is enabled, so your logs will not be written by timestamp. You can test with example, set 1000 in place of 100000, order will be random, depends on access to file.

此外,appendFile将在启用时写入,因此日志不会被时间戳写入。您可以使用示例进行测试,将1000设置为100000,顺序将是随机的,取决于对文件的访问。

If you want to append to a file, you must use a writable stream like this:

如果您想要附加到一个文件,您必须使用这样的可写流:

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

You end it when you want. You are not even required to use stream.end(), default option is AutoClose:true, so your file will end when your process ends and you avoid opening too many files.

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

#4


19  

You need to open it, then write to it.

你需要打开它,然后写它。

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

Here's a few links that will help explain the parameters

这里有一些可以帮助解释参数的链接。

open
write
close

打开写关闭


EDIT: This answer is no longer valid, look into the new fs.appendFile method for appending.

编辑:这个答案不再有效,请查看新的fs。appendFile附加的方法。

#5


16  

Besides appendFile, you can also pass a flag in writeFile to append data to an existing file.

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

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

By passing flag 'a', data will be appended at the end of the file.

通过传递标志“a”,数据将被添加到文件的末尾。

#6


13  

Node 0.8 has fs.appendFile:

节点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!');
});

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

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

#7


3  

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

#8


2  

Using jfile package :

使用jfile包:

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

#9


1  

I offer this suggestion only because control over open flags is sometimes useful, for example, you may want to truncate it an existing file first and then append a series of writes to it - in which case use the 'w' flag when opening the file and don't close it until all the writes are done. Of course appendFile may be what you're after :-)

我只提供这个建议因为控制开放旗帜有时候是有用的,例如,你可能想要截断它现有的文件,然后添加一系列写道——在这种情况下,使用“w”标志打开文件时,不要关闭它,直到所有的写操作都完成了。当然附件文件可能是你想要的:-)

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

#10


1  

If you want an easy and stress-free way to write logs line by line in a file, then I recommend fs-extra:

如果你想要一种简单且无压力的方式,在一个文件中一行一行地写日志,那么我推荐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');

Tested with Node v8.9.4.

测试节点v8.9.4。

#11


0  

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

#12


0  

an easier way to do this is

一个更简单的方法是

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

#1


519  

For occasional appends, you can use appendFile, which creates a new file handle each time it's called:

对于偶尔的附加文件,您可以使用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');

But if you append repeatedly to the same file, it's much better to reuse the file handle.

但是如果您重复地向同一个文件追加,那么最好重用文件句柄。

#2


96  

Your code using createWriteStream creates a file descriptor for every write. log.end is better because it asks node to close immediatelly after the write.

使用createWriteStream的代码为每次写入创建一个文件描述符。日志。结尾更好,因为它要求节点在写完后立即关闭。

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

#3


64  

When you want to write in a log file, i.e. appending data to the end of a file, never uses appendFile, appendFile opens a file handle for each piece of data you add to your file, after a while you get a beautiful EMFILE error.

当您想要在一个日志文件中写入时,也就是将数据附加到文件的末尾,不要使用appendFile, appendFile会为您添加到文件中的每一个数据打开一个文件句柄,稍后您会得到一个漂亮的EMFILE错误。

I can add that appendFile is not easier to use than a WriteStream.

我可以添加appendFile并不比WriteStream更容易使用。

Example with appendFile:

与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());

Up to 8000 on my computer, you can append data to the file, then you obtain this:

在我的电脑上最多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' }

Moreover, appendFile will write when it is enabled, so your logs will not be written by timestamp. You can test with example, set 1000 in place of 100000, order will be random, depends on access to file.

此外,appendFile将在启用时写入,因此日志不会被时间戳写入。您可以使用示例进行测试,将1000设置为100000,顺序将是随机的,取决于对文件的访问。

If you want to append to a file, you must use a writable stream like this:

如果您想要附加到一个文件,您必须使用这样的可写流:

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

You end it when you want. You are not even required to use stream.end(), default option is AutoClose:true, so your file will end when your process ends and you avoid opening too many files.

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

#4


19  

You need to open it, then write to it.

你需要打开它,然后写它。

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

Here's a few links that will help explain the parameters

这里有一些可以帮助解释参数的链接。

open
write
close

打开写关闭


EDIT: This answer is no longer valid, look into the new fs.appendFile method for appending.

编辑:这个答案不再有效,请查看新的fs。appendFile附加的方法。

#5


16  

Besides appendFile, you can also pass a flag in writeFile to append data to an existing file.

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

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

By passing flag 'a', data will be appended at the end of the file.

通过传递标志“a”,数据将被添加到文件的末尾。

#6


13  

Node 0.8 has fs.appendFile:

节点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!');
});

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

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

#7


3  

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

#8


2  

Using jfile package :

使用jfile包:

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

#9


1  

I offer this suggestion only because control over open flags is sometimes useful, for example, you may want to truncate it an existing file first and then append a series of writes to it - in which case use the 'w' flag when opening the file and don't close it until all the writes are done. Of course appendFile may be what you're after :-)

我只提供这个建议因为控制开放旗帜有时候是有用的,例如,你可能想要截断它现有的文件,然后添加一系列写道——在这种情况下,使用“w”标志打开文件时,不要关闭它,直到所有的写操作都完成了。当然附件文件可能是你想要的:-)

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

#10


1  

If you want an easy and stress-free way to write logs line by line in a file, then I recommend fs-extra:

如果你想要一种简单且无压力的方式,在一个文件中一行一行地写日志,那么我推荐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');

Tested with Node v8.9.4.

测试节点v8.9.4。

#11


0  

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

#12


0  

an easier way to do this is

一个更简单的方法是

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