Last active
January 15, 2026 12:40
-
-
Save lovasoa/8691344 to your computer and use it in GitHub Desktop.
Walk through a directory recursively in node.js.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // ES6 version using asynchronous iterators, compatible with node v10.0+ | |
| const fs = require("fs"); | |
| const path = require("path"); | |
| async function* walk(dir) { | |
| for await (const d of await fs.promises.opendir(dir)) { | |
| const entry = path.join(dir, d.name); | |
| if (d.isDirectory()) yield* walk(entry); | |
| else if (d.isFile()) yield entry; | |
| } | |
| } | |
| // Then, use it with a simple async for loop | |
| async function main() { | |
| for await (const p of walk('/tmp/')) | |
| console.log(p) | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Callback-based version for old versions of Node | |
| var fs = require("fs"), | |
| path = require("path"); | |
| function walk(dir, callback) { | |
| fs.readdir(dir, function(err, files) { | |
| if (err) throw err; | |
| files.forEach(function(file) { | |
| var filepath = path.join(dir, file); | |
| fs.stat(filepath, function(err,stats) { | |
| if (stats.isDirectory()) { | |
| walk(filepath, callback); | |
| } else if (stats.isFile()) { | |
| callback(filepath, stats); | |
| } | |
| }); | |
| }); | |
| }); | |
| } | |
| if (exports) { | |
| exports.walk = walk; | |
| } else { | |
| walk(".", manageFile); | |
| } |
snowinmars-debug
commented
Mar 11, 2025
TypeScript version, and bug fix (based es6 version)
import fs from "fs";
import path from "path";
async function walk(dir: string) {
const files = await fs.promises.readdir(dir);
const chunks: string[][] = await Promise.all(
files.map(async (file) => {
const filePath = path.join(dir, file);
const stats = await fs.promises.stat(filePath);
if (stats.isDirectory()) return walk(filePath);
else if (stats.isFile()) return [filePath];
return [];
})
);
return chunks.reduce((total, chunk) => total.concat(chunk), [] as string[]);
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment