how to use the readdir function from fs-extra in javascript

To use the readdir function from fs-extra, first install the module through npm using npm i fs-extra.

Then, require the fs-extra module and call the readdir function, passing in the directory path you want to read as the first parameter. The function will return a promise that resolves with an array of filenames in the directory.

Here's an example:

index.tsx
const fs = require('fs-extra');

fs.readdir('/path/to/dir')
  .then(files => {
    console.log(files); // array of filenames
  })
  .catch(err => {
    console.error(err);
  });
178 chars
10 lines

You can also pass in options as the second parameter to filter the results. For example, you can use the withFileTypes option to get information on each item in the directory, such as whether it is a file or directory:

index.tsx
fs.readdir('/path/to/dir', { withFileTypes: true })
  .then(files => {
    files.forEach(file => {
      if (file.isDirectory()) {
        console.log(`${file.name} is a directory`);
      } else {
        console.log(`${file.name} is a file`);
      }
    });
  })
  .catch(err => {
    console.error(err);
  });
314 chars
14 lines

gistlibby LogSnag