1

I've read that fs.appendFile doesn't return fd (file descriptor) so it opens the file and even closes for you. But in the example below i get error Error: EMFILE: too many open files, open

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

Which i assume means that for every new append it opens same file over and over. However with stream everything is fine

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

So, why in first case appendFile is not closing the file after the operation?

jack_snipe
  • 129
  • 1
  • 11

1 Answers1

2

As you may know fs.appendFile is asynchronous. So in the code you call fs.appendFile 10000 times at the same time.

You just need to wait for the first append to finish before you append again.

This should work:

var index = 0;
function append(){
    fs.appendFile("append.txt", index+ "\n", function (err) {
        index++;
        if (index < 10000)
            append();
        else
            console.log('Done');
    });
};
append();

Also note that this is very bad for performance.

Molda
  • 5,619
  • 2
  • 23
  • 39