Fixing node error “EMFILE: too many open files”

I’ve found that sometimes when I write scripts in Node, I get errors like this:

Loading info: Error: EMFILE: too many open files, 
open 'D:\projects\image-annotation\data\youtube\videos\ZX8MBBohX3s.info.json'

Typically this is caused by invalid uses of “readFile” or “writeFile”, like so:

writeFile("json/1/" + itemNumber + ".json", 
  JSON.stringify(result, null, 2),            
  (err) => {
    if(err) {
     return console.log(err);
    }
});

The reason that this doesn’t work is that the call is asynchronous – you’re supposed to provide a callback for success, and close the file there.

If you don’t want to do this, you can easily fix this by using the “sync” methods:

writeFileSync("json/1/" + itemNumber + ".json", 
     JSON.stringify(result, null, 2));

In this case you don’t need the error handler, because errors will be thrown.

Leave a Reply

Your email address will not be published. Required fields are marked *