In this tutorial, you will learn how to find and list all directories in a directory in node js using third party libraries and built in methods.
List All Directories in a Directory in Node.js
Here are three common approaches to getting a list of all directories in the directory in the node.js; as follows:
Method 1: Using the fs
module (Asynchronous)
Using the fs
module, you can list all directories in a directory asynchronously in node js. Here is an example that uses the fs.readdir()
method to list all directories in the current directory:
const fs = require('fs');
// Define the directory path
const directoryPath = './myDirectory';
// Use fs.readdir to read the contents of the directory
fs.readdir(directoryPath, { withFileTypes: true }, (err, files) => {
if (err) {
console.error('Error reading directory:', err);
return;
}
// Filter out the directories
const directories = files.filter(file => file.isDirectory());
// Print the directory names
directories.forEach(directory => {
console.log(directory.name);
});
});
Method 2: Using the fs
module (Synchronous)
Using the fs
module, you can list all directories in a directory Synchronous in node js. Here is an example that uses the fs.readdirSync()
method to list all directories in the current directory:
const fs = require('fs');
// Define the directory path
const directoryPath = './myDirectory';
try {
const files = fs.readdirSync(directoryPath, { withFileTypes: true });
// Filter out the directories
const directories = files.filter(file => file.isDirectory());
// Print the directory names
directories.forEach(directory => {
console.log(directory.name);
});
} catch (err) {
console.error('Error reading directory:', err);
}
Method 3: Using the fs-extra
library
Using the fs-extra
library, you can list all directories in a directory in node js. Here is an example that uses the
method to list all directories in the current directory:fs-extra
library
const fs = require('fs-extra');
// Define the directory path
const directoryPath = './myDirectory';
// Use fs.readdir to read the contents of the directory
fs.readdir(directoryPath, (err, files) => {
if (err) {
console.error('Error reading directory:', err);
return;
}
// Filter out the directories
const directories = files.filter(file => fs.statSync(file).isDirectory());
// Print the directory names
directories.forEach(directory => {
console.log(directory);
});
});
Conclusion
That’s it; you have learned three different methods for listing directories in a directory in Node.js.