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:

  • files is an array of filenames.
  • path is the path to the target directory.
  • withFileTypes is an optional boolean used to return fs.Dirent objects instead of strings, including the type of each file.
  • recursive is an optional boolean used to recursively list the content of the target directory.

Note: This function is similar to the Unix ls command.

Example

Let's consider this script that generates a visual tree-like structure of a directory:

tree.js
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:

  1. Output the path to the target directory.
  2. Invoke the recursive generateTree() function with the path to the target directory and the depth set to zero, which represents the top-level directory.
  3. Get the filenames of the entries present in the current directory.
  4. Output each filename and check if the entry is a directory.
  5. 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:

  • path is the relative or absolute path to the directory you want to create.
  • recursive is an optional boolean used to determine whether the parent directories should be created.
  • mode is an optional octal number used to set the directory permissions.

Note: This function is similar to the Unix mkdir command.

Example

Let's consider this script that creates a standard directory structure for a Node.js project:

create_project.js
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:

  1. Loop on each relative filepath present in the dirPaths variable.
  2. Create the full path to the subdirectory by concatenating the baseDir and dirPaths variables.
  3. 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 returns true and ignores it otherwise.

Note: This function is similar to the Unix cp -r command.

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:

  1. Recursively loop on every entry of the project directory.
  2. Copy the entries that are directories or regular files with a .js file extension into the backup directory using the filter option.

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:

  • path is the path to the target directory.

Note: This function is similar to the Unix rmdir command.

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:

  • path is the path to the target directory.
  • recursive is an optional boolean used to recursively delete files.

Note: This function is similar to the Unix rm -r command.

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
Work With Directories in Node.js | Backend Brewery