node and Error: EMFILE, too many open files

For some days I have searched for a working solution to an error

Error: EMFILE, too many open files

It seems that many people have the same problem. The usual answer involves increasing the number of file descriptors. So, I’ve tried this:

sysctl -w kern.maxfiles=20480

The default value is 10240. This is a little strange in my eyes, because the number of files I’m handling in the directory is under 10240. Even stranger, I still receive the same error after I’ve increased the number of file descriptors.

Second question:

After a number of searches I found a work around for the “too many open files” problem:

var requestBatches = {};
function batchingReadFile(filename, callback) {
  // First check to see if there is already a batch
  if (requestBatches.hasOwnProperty(filename)) {
    requestBatches[filename].push(callback);
    return;
  }

  // Otherwise start a new one and make a real request
  var batch = requestBatches[filename] = [callback];
  FS.readFile(filename, onRealRead);
  
  // Flush out the batch on complete
  function onRealRead() {
    delete requestBatches[filename];
    for (var i = 0, l = batch.length; i < l; i++) {
      batch[i].apply(null, arguments);
    }
  }
}

function printFile(file){
    console.log(file);
}

dir = "/Users/xaver/Downloads/xaver/xxx/xxx/"

var files = fs.readdirSync(dir);

for (i in files){
    filename = dir + files[i];
    console.log(filename);
    batchingReadFile(filename, printFile);

Unfortunately I still recieve the same error.
What is wrong with this code?

24 Answers
24

Leave a Comment