Open
Description
- Node.js Version: 14.17.0 & 16.2.0
- Module (and version) (if relevant):
fs/promises
I tried to cleanup the unclosed FileHandle
using the FinalizationRegistry
as shown in the following code example.
test.mjs
import { close } from 'fs';
import { open } from 'fs/promises';
const registry = new FinalizationRegistry(fd => {
console.log('FinalizationRegistry callback');
close(fd, err => {
// console.log(err); // [Error: EBADF: bad file descriptor, close]
});
});
let fileHandle = await open('/path/to/file', 'r');
// register the file descriptor
registry.register(fileHandle, fileHandle.fd);
// release the reference intentionally
setTimeout(() => fileHandle = null, 1000);
// run garbage collector
setTimeout(() => global?.gc?.(), 2000);
await new Promise(_ => setTimeout(_, 3000));
However, before the FinalizationRegistry
callback is executed, the node.js "auto-closing" is run and warned.
$ node --expose-gc test.mjs
(node:6796) Warning: Closing file descriptor 3 on garbage collection
(Use `node --trace-warnings ...` to show where the warning was created)
(node:6796) [DEP0137] DeprecationWarning: Closing a FileHandle object on garbage collection is deprecated. Please close FileHandle objects explicitly using FileHandle.prototype.close(). In the future, an error will be thrown if a file descriptor is closed during garbage collection.
This "auto-closing" is a great feature for safety reasons, but if the developer has implemented their own cleanup process, could you delay the timing of its execution a bit so that it doesn't get warned?
I would be happy if you will consider it.