List all directories in a directory in Node.js [4 Ways]

avatar
Borislav Hadzhiev

Last updated: Apr 5, 2024
5 min

banner

# Table of Contents

  1. List all directories in a directory in Node.js
  2. List all directories in a directory Synchronously in Node.js
  3. List all directories in a directory recursively in Node.js
  4. List all directories in a directory Asynchronously with Callbacks

Note: if you need to list all directories in a directory recursively, click on the following subheading:

# List all directories in a directory in Node.js

To list all directories in a directory in Node.js:

  1. Use the fsPromises.readdir() method to read the contents of the directory.
  2. Use the filter() method to only return an array containing the directories.
  3. Use the map() method to return an array containing the names of the directories.
index.js
// ๐Ÿ‘‡๏ธ using import/export syntax import {readdir} from 'fs/promises'; import path from 'path'; import {fileURLToPath} from 'url'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); async function listDirectories(pth) { const directories = (await readdir(pth, {withFileTypes: true})) .filter(dirent => dirent.isDirectory()) .map(dir => dir.name); return directories; } console.log(await listDirectories('./')); // [ // '.git', // '.vscode', // 'controllers', // 'node_modules', // 'pages', // 'routes', // 'src', // 'views' // ] console.log(await listDirectories(__dirname));

get all directories within directory in node

The code for this article is available on GitHub

The code sample above uses top-level await, however, you can also use the .then syntax.

index.js
// ๐Ÿ‘‡๏ธ using import/export syntax import {readdir} from 'fs/promises'; import path from 'path'; import {fileURLToPath} from 'url'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); async function listDirectories(pth) { const directories = (await readdir(pth, {withFileTypes: true})) .filter(dirent => dirent.isDirectory()) .map(dir => dir.name); return directories; } // โœ… Using .then() syntax instead listDirectories('./').then(directories => { console.log(directories); }); // [ // '.git', // '.vscode', // 'controllers', // 'node_modules', // 'pages', // 'routes', // 'src', // 'views' // ] listDirectories(__dirname).then(directories => { console.log(directories); });
The code for this article is available on GitHub

The examples above use the ES6 import/export syntax.

If you use the CommonJS require() syntax, use the following code sample instead.

index.js
// ๐Ÿ‘‡๏ธ using CommonJS require() syntax const {readdir} = require('fs/promises'); async function listDirectories(pth) { const directories = (await readdir(pth, {withFileTypes: true})) .filter(dirent => dirent.isDirectory()) .map(dir => dir.name); return directories; } listDirectories('./').then(directories => { console.log(directories); }); listDirectories(__dirname).then(directories => { console.log(directories); }); // [ // '.git', // '.vscode', // 'controllers', // 'node_modules', // 'pages', // 'routes', // 'src', // 'views' // ] console.log(__dirname);

The listDirectories() function takes a path and returns an array containing the directories in the given path.

We used the fsPromises.readdir method to get an array of the files and folders in a given directory.

index.js
async function listDirectories(pth) { const directories = (await readdir(pth, {withFileTypes: true})) .filter(dirent => dirent.isDirectory()) .map(dir => dir.name); return directories; }

The first argument the method takes is a path and the second is an options object.

We set the withFileTypes argument to true so the resolved array contains fs.Dirent objects.

The next step is to use the Array.filter method to get an array that only contains the directories.

The last step is to use the Array.map method to get the names of the directories.

You can use the __dirname global variable if you need to access the directory of the current script.

index.js
import path from 'path'; import {fileURLToPath} from 'url'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); // ๐Ÿ‘‡๏ธ /home/borislav/Desktop/bobbyhadz-js/index.js console.log(__filename); // ๐Ÿ‘‡๏ธ /home/borislav/Desktop/bobbyhadz-js console.log(__dirname);
The code for this article is available on GitHub

The path.dirname() method takes a path as a parameter and returns the directory name of the path.

If you use the CommonJS require() syntax, you can use the __dirname variable directly in your code.

index.js
// ๐Ÿ‘‡๏ธ /home/borislav/Desktop/bobbyhadz-js console.log(__dirname); // ๐Ÿ‘‡๏ธ /home/borislav/Desktop/bobbyhadz-js/index.js console.log(__filename);

# List all directories in a directory Synchronously in Node.js

You can use a similar approach to list all directories in a directory synchronously in Node.js.

index.js
import {readdirSync} from 'fs'; import path from 'path'; import {fileURLToPath} from 'url'; const __filename = fileURLToPath(import.meta.url); const __dirname = path.dirname(__filename); function listDirectories(pth) { return readdirSync(pth, {withFileTypes: true}) .filter(dirent => dirent.isDirectory()) .map(dirent => dirent.name); } console.log(listDirectories('./')); // [ // '.git', // '.vscode', // 'controllers', // 'node_modules', // 'pages', // 'routes', // 'src', // 'views' // ] console.log(listDirectories(__dirname));

list all directories in a directory synchronously in node

The code for this article is available on GitHub

The listDirectories() function takes a path to a directory and returns all directories in the given path synchronously.

The example above uses the ES6 import/export syntax.

If you use CommonJS require(), use the following code sample instead.

index.js
const {readdirSync} = require('fs'); function listDirectories(pth) { return readdirSync(pth, {withFileTypes: true}) .filter(dirent => dirent.isDirectory()) .map(dirent => dirent.name); } console.log(listDirectories('./')); // [ // '.git', // '.vscode', // 'controllers', // 'node_modules', // 'pages', // 'routes', // 'src', // 'views' // ] console.log(listDirectories(__dirname));

Notice that we imported the fs.readdirSync method this time.

index.js
import {readdirSync} from 'fs'; function listDirectories(pth) { return readdirSync(pth, {withFileTypes: true}) .filter(dirent => dirent.isDirectory()) .map(dirent => dirent.name); }
The code for this article is available on GitHub

The fs.readdirSync() method takes a path and an options object and reads the contents of the directory.

If the withFileTypes property is set to true, the result contains fs.Dirent objects.

We then used the filter() and map() methods to get the names of the directories in the given path just like in the previous subheading.

# List all directories in a directory recursively in Node.js

If you need to list all directories in a directory recursively, use the following code sample instead.

index.js
import fs from 'fs'; import path from 'path'; // ๐Ÿ‘‡๏ธ if you use CommonJS require() // const fs = require('fs') // const path = require('path') function getDirectories(dirpath) { const directoriesToExclude = ['node_modules', '.git']; return fs .readdirSync(dirpath) .map(file => path.join(dirpath, file)) .filter( pth => fs.statSync(pth).isDirectory() && !directoriesToExclude.includes(pth), ); } function getDirectoriesRecursive(dirpath) { return [ dirpath, ...flatten( getDirectories(dirpath).map(getDirectoriesRecursive), ), ]; } function flatten(arr) { return arr.slice().flat(); } // [ // './', // '.vscode', // 'controllers', // 'pages', // 'pages/private', // 'pages/public', // 'routes', // 'src', // 'src/utils', // 'views' // ] console.log(getDirectoriesRecursive('./'));

list all directories in a directory recursively and synchronously

The code for this article is available on GitHub

Make sure to specify the directories you want to exclude, e.g. node_modules and .git.

index.js
function getDirectories(dirpath) { const directoriesToExclude = ['node_modules', '.git']; return fs .readdirSync(dirpath) .map(file => path.join(dirpath, file)) .filter( pth => fs.statSync(pth).isDirectory() && !directoriesToExclude.includes(pth), ); }

# List all directories in a directory Asynchronously with Callbacks

If you prefer using the asynchronous syntax with callbacks, use the following code snippet instead.

index.js
import {readdir} from 'fs'; // ๐Ÿ‘‡๏ธ if you use CommonJS require() // const {readdir} = require('fs') const pth = './'; readdir(pth, {withFileTypes: true}, (error, files) => { if (error) { console.log(error); } else { const directories = files .filter(dirent => dirent.isDirectory()) .map(directory => directory.name); console.log(directories); } });

list all directories in a directory using callbacks

The code for this article is available on GitHub

Notice that we imported the readdir() method from the fs module, not from fs/promises.

The function takes 3 parameters:

  1. the path to the directory.
  2. an options object.
  3. a callback function that gets called with an error (or null if there's no error) and an array of files.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev