Work With Directories in Node.js
13 min read·Jan 1, 2025
Read the content of a directory
To list the content of a directory, you can use the fs.readdirSync() static method:
const files = fs.readdirSync(path, { withFileTypes?, recursive? });
Where:
filesis an array of filenames.pathis the path to the target directory.withFileTypesis an optional boolean used to returnfs.Direntobjects instead of strings, including the type of each file.recursiveis an optional boolean used to recursively list the content of the target directory.
Note: This function is similar to the Unix
lscommand.
Example
Let's consider this script that generates a visual tree-like structure of a directory:
const fs = require('node:fs');
const path = require('node:path');
function generateTree(dirPath, depth = 0) {
try {
const fileNames = fs.readdirSync(dirPath);
const prefix = '│ '.repeat(depth);
fileNames.forEach((fileName, index) => {
const filePath = path.join(dirPath, fileName);
const fileStats = fs.statSync(filePath);
const filePrefix = (index === fileNames.length - 1) ? '└── ' : '├── ';
console.log(prefix + filePrefix + fileName);
if (fileStats.isDirectory()) {
generateTree(filePath, depth + 1);
}
});
} catch(error) {
console.error(error);
}
}
const dir = '/Users/razvan/Documents';
console.log(dir);
generateTree(dir);
When executed, it will:
- Output the path to the target directory.
- Invoke the recursive
generateTree()function with the path to the target directory and the depth set to zero, which represents the top-level directory. - Get the filenames of the entries present in the current directory.
- Output each filename and check if the entry is a directory.
- If the entry is directory, call the
generateTree()function with the full path to the subdirectory and set the depth to the current depth + 1.
Which will produce this output:
$ node tree.js
.
├── backups
│ ├── 20241114_customers.csv
│ └── 20241114_orders.csv
├── data
│ ├── customers.csv
│ └── orders.csv
└── script.js
Create directories
To create a new directory, you can use the fs.mkdirSync() static method:
fs.mkdirSync(path, { recursive?, mode? });
Where:
pathis the relative or absolute path to the directory you want to create.recursiveis an optional boolean used to determine whether the parent directories should be created.modeis an optional octal number used to set the directory permissions.
Note: This function is similar to the Unix
mkdircommand.
Example
Let's consider this script that creates a standard directory structure for a Node.js project:
const fs = require('node:fs');
const path = require('node:path');
function createProject(baseDir) {
const dirPaths = [
'src',
'src/lib',
'src/utils',
'bin',
'docs'
];
try {
dirPaths.forEach(dirPath => {
const fullPath = path.join(baseDir, dirPath);
console.log(`Creating directory '${fullPath}'`);
fs.mkdirSync(fullPath, { recursive: true });
});
} catch(error) {
console.error(error);
}
}
createProject('./project');
When executed, it will:
- Loop on each relative filepath present in the
dirPathsvariable. - Create the full path to the subdirectory by concatenating the
baseDiranddirPathsvariables. - Recursively create the subdirectory.
Which will produce this output:
$ node create_project.js
Creating directory 'project/src'
Creating directory 'project/src/lib'
Creating directory 'project/src/utils'
Creating directory 'project/bin'
Creating directory 'project/docs'
And create this directory structure:
./project
├── bin
├── docs
└── src
│ ├── lib
│ └── utils
Copy directories
To copy a directory, including its files and subdirectories, you can use the fs.cpSync() static method:
fs.cpSync(src, dest, { recursive: true, filter? });
Where:
filter(src, dst)is an optional function that copies the current file/directory if it returnstrueand ignores it otherwise.
Note: This function is similar to the Unix
cp -rcommand.
Example
Let's consider this script that only copies directories and JavaScript files:
const fs = require('node:fs');
try {
fs.cpSync('./project', './backup', {
recursive: true,
filter: (src, dst) => {
const stats = fs.statSync(src);
return stats.isDirectory() || (stats.isFile() && src.endsWith('.js'));
}
});
} catch(error) {
console.error(error);
}
When executed, it will:
- Recursively loop on every entry of the
projectdirectory. - Copy the entries that are directories or regular files with a
.jsfile extension into thebackupdirectory using thefilteroption.
Remove directories
To remove a directory, you can use the fs.rmdirSync() and fs.rmSync() static method.
Remove empty directories
To remove an empty directory, you can use the fs.rmdirSync() static method:
fs.rmdirSync(path);
Where:
pathis the path to the target directory.
Note: This function is similar to the Unix
rmdircommand.
Remove non-empty directories
To remove a non-empty directory, including its files and subdirectories, you can use the fs.rmSync() static method:
fs.rmSync(path, { recursive: true });
Where:
pathis the path to the target directory.recursiveis an optional boolean used to recursively delete files.
Note: This function is similar to the Unix
rm -rcommand.
Summary
Here's a summary of what you've learned in this lesson:
- The
fs.readdirSync()function is used to list the content of directories. - The
fs.mkdirSync()function is used to create directories. - The
fs.cpSync()function is used to copy directories. - The
fs.rmdirSync()function is used to remove empty directories. - The
fs.rmSync()function is used to remove any directories.
Enjoying the courses?
I've made these courses completely free so anyone can learn from them. If they've helped you and you'd like to actively support the work behind BackendBrewery, you can leave a tip:
Support BackendBrewery