Last updated: Apr 5, 2024
Reading timeยท5 min
Note: if you need to list all directories in a directory
recursively
, click on the following subheading:
To list all directories in a directory in Node.js:
fsPromises.readdir()
method to read the contents of the directory.filter()
method to only return an array containing the directories.map()
method to return an array containing the names of the
directories.// ๐๏ธ 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));
The code sample above uses top-level await, however, you can also use the .then syntax.
// ๐๏ธ 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 examples above use the ES6 import/export syntax.
If you use the CommonJS require()
syntax, use the following code sample
instead.
// ๐๏ธ 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.
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.
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 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.
// ๐๏ธ /home/borislav/Desktop/bobbyhadz-js console.log(__dirname); // ๐๏ธ /home/borislav/Desktop/bobbyhadz-js/index.js console.log(__filename);
You can use a similar approach to list all directories in a directory synchronously in Node.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));
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.
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.
import {readdirSync} from 'fs'; function listDirectories(pth) { return readdirSync(pth, {withFileTypes: true}) .filter(dirent => dirent.isDirectory()) .map(dirent => dirent.name); }
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.
If you need to list all directories in a directory recursively, use the following code sample instead.
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('./'));
Make sure to specify the directories you want to exclude, e.g. node_modules
and .git
.
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), ); }
If you prefer using the asynchronous syntax with callbacks, use the following code snippet instead.
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); } });
Notice that we imported the
readdir()
method from the fs
module, not from fs/promises
.
The function takes 3 parameters:
options
object.null
if there's no
error) and an array of files.You can learn more about the related topics by checking out the following tutorials: