(libuv) kqueue(): Too many open files in system when trying to write a file in Node Js
<p>When I use fs.appendFile to save a lot of records from the DB I get an error. Here is the code:</p>

<pre><code>var query = 'SELECT * FROM Messages LIMIT 10000';
    connection.query(query, function(err, rows, fields){
        if(err) throw err;
        connection.end();

    for (var i = 0; i &lt; rows.length; i++) {

        fs.appendFile('somefile.json', '{"index" : {"_index" : "mymessages" , "_type" : "data" , "_id" : "'+rows[i].message_id+'"}} \n' + JSON.stringify(rows[i]) + '\n', function (err) {
        if (err) return console.log(err);
            //console.log(err);
        });


    }

    console.log('Added: ' + rows.length);


});
</code></pre>

<p>The error: </p>

<pre>
node es.js (libuv) kqueue(): Too many open files in system (libuv) kqueue(): Too many open files in system /private/var/www/mail-listener/node_modules/mysql/lib/protocol/Parser.js:77
        throw err; // Rethrow non-MySQL errors
              ^ Error: write EBADF
    at exports._errnoException (util.js:746:11)
    at WriteStream.Socket._writeGeneric (net.js:681:26)
    at WriteStream.Socket._write (net.js:700:8)
    at doWrite (_stream_writable.js:301:12)
    at writeOrBuffer (_stream_writable.js:288:5)
    at WriteStream.Writable.write (_stream_writable.js:217:11)
    at WriteStream.Socket.write (net.js:625:40)
    at Console.log (console.js:55:16)
    at Query._callback (/private/var/www/mail-listener/es.js:114:11)
    at Query.Sequence.end (/private/var/www/mail-listener/node_modules/mysql/lib/protocol/sequences/Sequence.js:96:24)
</pre>