Categories
JavaScript Answers

How to get all directories within directory with Node.js?

Spread the love

Sometimes, we want to get all directories within directory with Node.js.

In this article, we’ll look at how to get all directories within directory with Node.js.

How to get all directories within directory with Node.js?

To get all directories within directory with Node.js, we can use the readdir method.

For instance, we write

const {
  promises: {
    readdir
  }
} = require('fs')

const getDirectories = async source => {
  const dirs = await readdir(source, {
    withFileTypes: true
  })
  return dirs
    .filter(dirent => dirent.isDirectory())
    .map(dirent => dirent.name)
}

to create the getDirections function that takes the source path string.

In it, we call readdir with source and an object that has withFileTypes set to true to return the file types with the items.

Then we call isDirectory to return an array of directories in the source folder and call map to return the names of each folder.

Conclusion

To get all directories within directory with Node.js, we can use the readdir method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *