Iterate Over Files and Directories in Node.js

Node.js provides powerful tools to access and manipulate the file system. Iterating over files and directories is a common operation, for example, to build a file management system, data analysis, or automated deployments.

Using the fs Module

The fs (file system) module is part of Node.js's standard library. There are two main approaches to working with files and directories: asynchronous and synchronous.

Listing Files in a Directory

const fs = require('fs');
const path = require('path');

const directoryPath = path.join(__dirname, 'mydirectory');

fs.readdir(directoryPath, (err, files) => {
  if (err) {
    return console.error('Error reading the directory:', err);
  }
  files.forEach(file => {
    console.log(file);
  });
});

Recursively Reading a Directory

const fs = require('fs');
const path = require('path');

function readDirectoryRecursive(dir) {
  fs.readdir(dir, { withFileTypes: true }, (err, entries) => {
    if (err) {
      console.error('Error:', err);
      return;
    }

    entries.forEach(entry => {
      const fullPath = path.join(dir, entry.name);
      if (entry.isDirectory()) {
        readDirectoryRecursive(fullPath);
      } else {
        console.log(fullPath);
      }
    });
  });
}

readDirectoryRecursive(path.join(__dirname, 'mydirectory'));

Synchronous Version

function readDirectoryRecursiveSync(dir) {
  const entries = fs.readdirSync(dir, { withFileTypes: true });
  for (const entry of entries) {
    const fullPath = path.join(dir, entry.name);
    if (entry.isDirectory()) {
      readDirectoryRecursiveSync(fullPath);
    } else {
      console.log(fullPath);
    }
  }
}

readDirectoryRecursiveSync(path.join(__dirname, 'mydirectory'));

Conclusion

Iterating over files and directories in Node.js is simple and flexible thanks to the fs module. Asynchronous versions are preferable in high-performance environments, while synchronous ones can be useful for simple scripts or initial operations.

Back to top