Node.js › File System & File Processing
How would you recursively read all files within a directory tree in Node.js?
IntermediateAnswer
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.