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.

Interested in JavaScript? I send out weekly, personalized emails with articles and conference talks. Click here to see an example and subscribe.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

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