Skip to content

Creating and recognizing fs/promises FileHandle objects #43821

Description

@mvduin

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:

  1. test whether a value is a FileHandle
  2. 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.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature requestIssues requesting new Node.js features.fsIssues and PRs related to file-system APIs and the fs module.staleIssues and PRs marked stale due to inactivity and scheduled for automatic closure.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions