how to use the opendir function from the fs-extra library in typescript

To use the opendir function from the fs-extra library in TypeScript, you first need to install the library by running the following command:

index.ts
npm install --save fs-extra
28 chars
2 lines

After installing the library, you can import the opendir function from the fs-extra library and use it in your TypeScript code as follows:

index.ts
import { opendir } from 'fs-extra';

async function listFiles(path: string) {
  const dir = await opendir(path);
  for await (const dirent of dir) {
    console.log(dirent.name);
  }
}
185 chars
9 lines

In the above code:

  • We import the opendir function from the fs-extra library using ES6 import statements.
  • We define an async function named listFiles that takes a path parameter.
  • Inside the listFiles function, we call the opendir function with the path parameter and await the returned Dir object.
  • We then iterate over the Dirent objects in the directory using a for await...of loop and log each file or folder name to the console.

Note that using opendir requires Node.js version 12 or later.

gistlibby LogSnag