Advertisement
Advanced Node.js, File System & File Processing

How would you implement a directory-size calculator in Node.js that recursively sums the size of all files within a directory tree?

Short answer

A recursive function reads each directory's entries, and for each entry either adds its file size directly (if it's a file) or recurses into it (if it's a directory), accumulating a running total -- for very large directory trees, doing this recursion with concurrent async…

Save Node.js mock interview
Advertisement
AModel answer
A recursive function reads each directory's entries, and for each entry either adds its file size directly (if it's a file) or recurses into it (if it's a directory), accumulating a running total -- for very large directory trees, doing this recursion with concurrent async operations (rather than strictly sequential) can significantly speed up the process, though care must be taken not to open too many file handles simultaneously.
async function getDirectorySize(dirPath) {
  const entries = await fs.promises.readdir(dirPath, { withFileTypes: true });
  const sizes = await Promise.all(entries.map(async (entry) => {
    const fullPath = path.join(dirPath, entry.name);
    if (entry.isDirectory()) return getDirectorySize(fullPath);
    const stats = await fs.promises.stat(fullPath);
    return stats.size;
  }));
  return sizes.reduce((sum, size) => sum + size, 0);
}
Real-world example
A disk-usage reporting tool for a file-hosting service recursively calculates each user's total storage usage using concurrent async directory traversal, processing a large nested folder structure significantly faster than an equivalent purely sequential implementation would.
Likely follow-ups
  • What's the risk of unbounded concurrency when recursing into a directory tree with tens of thousands of files, and how would you cap it?
  • How does this approach handle symbolic links that might create circular references within the directory tree?
Related topics