-
-
Notifications
You must be signed in to change notification settings - Fork 33.6k
Description
What is the problem this feature will solve?
I have modules that both accept and produce raw file descriptors. It would be nice to be able to leverage the fs/promises FileHandle wrapper to help prevent accidental file descriptor leaks due to user error. Unfortunately there is no clean way to wrap a raw file descriptor into a FileHandle nor to even reliably recognize a FileHandle when passed as argument.
The following wrapper around fs/promises adds functions for these purposes:
import fsp from 'fs/promises';
let fh = await fsp.open('/dev/null');
const FileHandle = fh.constructor;
const [ kHandle ] = Reflect.ownKeys( fh ).filter( k => typeof k === 'symbol' && k.description === 'kHandle' );
const RealFileHandle = fh[ kHandle ].constructor;
fh.close();
fh = null;
export * from 'fs/promises';
export const isFileHandle = ( arg ) => arg instanceof FileHandle;
export const fdopen = ( fd ) => new FileHandle( new RealFileHandle( fd ) );but needless to say this is horrifying.
What is the feature you are proposing to solve the problem?
Either add two functions to:
- test whether a value is a FileHandle
- create a FileHandle from a file descriptor
or export the FileHandle class and change its constructor to support new FileHandle( fd )
What alternatives have you considered?
Reimplementing similar functionality is possible using WeakRefs and FinalizationRegistry, but it seems unproductive to make an incompatible reimplementation of a class that's already implemented by nodejs itself, and it doesn't fix the problem of recognizing instances of the nodejs FileHandle when a user passes one.