Back to results for “File System”
Node.js › File System & File Processing

How would you recursively read all files within a directory tree in Node.js?

Intermediate

Answer

fs.readdir() with the 'recursive' option (Node 20+) returns every file and subdirectory path within a directory tree in one call, or for finer control (like filtering or processing files as they're discovered rather than all at once), you can manually walk the tree, calling fs.readdir() on each directory and recursing into any subdirectories found.
const fs = require('node:fs/promises');

const files = await fs.readdir('./project', { recursive: true, withFileTypes: true });
const jsFiles = files.filter(f => f.isFile() && f.name.endsWith('.js'));
Real-world example A code-linting tool recursively scans an entire project directory for all .js files using fs.readdir with the recursive option, avoiding the need to manually implement tree-walking logic that used to require a third-party package like glob.

Common follow-ups: How does the recursive option's behavior differ across Node.js versions where it wasn't yet available?;What's the performance consideration of reading an entire deep directory tree into memory at once versus processing it incrementally?