Is fs.Dir eventually released when out of scope

33 Views Asked by At

I understood from another question that fs.FileHandle's OS file handle is never released automatically, even by the garbage collector ; and that code like this:

const file = await fs.open(path);
// do something with file
await file.close();

will eventually crash the application with EMFILE: too many open files if errors repeatedly occur while doing something with the file without closing it.

Note: the answer is from 2016. Does it still apply 7 years later?

My question is, does the same thing apply for fs.Dir?

const dir = await fs.opendir(path);

for await (let entry of dir) {
    // do something with entry
}

Here, dir is supposed to be closed automatically when the async iterator reaches the end (as seen in this question (NodeJS fs source code).

Will it also never be closed if an error occurs during // do something with entry?

1

There are 1 best solutions below

2
On BEST ANSWER

fs.Dir will "self" close at the end of the for/of iteration (e.g. when the iterator finishes).

But, if you don't let the iterator go to the end, you will have to call .close() on the fs.Dir object. Doc on that is here.

Nodejs does not currently close system resources when something is garbage collected. They are probably working towards being able to do that in the future (by adding some hooks into the GC system), but that is not something that happens now. You have to either be using some higher level function that closes the system resource for you automatically when the operation completes (such as a stream might do with a file handle) or you have to manually make sure you call the appropriate method for that resource to release it such as .close() in all code paths.

Will it also never be closed if an error occurs during Will it also never be closed if an error occurs during // do something with entry?

It is up to you to catch errors that happen in your own handling of the iteration and either continue with the iterator after your error, allowing it to finish the iteration and then autoClose or you have to manually call .close() on the fs.Dir if you're aborting the iteration early.

Garbage collection will not call close on the OS handle for you.