Workbench

How to get a node.js Dirent object directly from a path

I found myself needing a Dirent object for a known path, and as far as I can tell there's no way to instantiate one; although you can do:

const myDirEnt = new Dirent();
myDirent.name = '/path/to/a/file.txt';
myDirent.path = myDirent.parentPath = '/path/to/a/';

The isFile(), isDirectory(), etc. methods all return false.

So, I wrote a function returns a functional Dirent object:

import fs from "fs/promises";

/**
 * Utility function to get a `Dirent` object for a given path without using `fs.readdir`
 */
const getDirent = async (filePath: PathLike): Promise<Dirent> => {
  const stat = await fs.lstat(filePath);
  const pathInfo = path.parse(filePath as string);
  return {
    name: pathInfo.base,
    path: pathInfo.dir,
    parentPath: pathInfo.dir,
    isDirectory: () => stat.isDirectory(),
    isFile: () => stat.isFile(),
    isSymbolicLink: () => stat.isSymbolicLink(),
    isBlockDevice: () => stat.isBlockDevice(),
    isCharacterDevice: () => stat.isCharacterDevice(),
    isFIFO: () => stat.isFIFO(),
    isSocket: () => stat.isSocket(),
  }
}

Thu Nov 07 2024 19:00:00 GMT-0500 (Eastern Standard Time)