Skip to content

Instantly share code, notes, and snippets.

@lovasoa
Last active March 11, 2025 15:15
Show Gist options
  • Save lovasoa/8691344 to your computer and use it in GitHub Desktop.
Save lovasoa/8691344 to your computer and use it in GitHub Desktop.
Walk through a directory recursively in node.js.
// 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)
}
// 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
Copy link

$ yarn add glob rxjs

/* --- */

import {Observable, of} from 'rxjs';
import { mergeMap } from 'rxjs/operators';
import * as path from 'path';
import {glob, type GlobOptionsWithFileTypesUnset} from "glob";

const listFiles = (root: string, globMask = '*', ignoredFolders: string[] = []): Observable<string> => {
  const ignore = ignoredFolders.map(x => path.join(root, x));
  const options: GlobOptionsWithFileTypesUnset = {
    cwd: root,
    nodir: true,
    ignore: ignore,
  };

  // do not use path.join as it uses upper slash instead of lower slash, and it does not work
  return of(globMask).pipe(
    mergeMap(x=> glob(x, options)),
    mergeMap(x => x),
  );
}

/* --- */

const topLevel = listFiles('/dev/sdb', '*.ts', []).subscribe(x => { console.log(x); });
const recurse = listFiles('/dev/sdb', '**/*.ts', []).subscribe(x => { console.log(x); });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment