Created
September 22, 2013 09:04
-
Star
(263)
You must be signed in to star a gist -
Fork
(45)
You must be signed in to fork a gist
-
-
Save kethinov/6658166 to your computer and use it in GitHub Desktop.
List all files in a directory in Node.js recursively in a synchronous fashion
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
// List all files in a directory in Node.js recursively in a synchronous fashion | |
var walkSync = function(dir, filelist) { | |
var fs = fs || require('fs'), | |
files = fs.readdirSync(dir); | |
filelist = filelist || []; | |
files.forEach(function(file) { | |
if (fs.statSync(dir + file).isDirectory()) { | |
filelist = walkSync(dir + file + '/', filelist); | |
} | |
else { | |
filelist.push(file); | |
} | |
}); | |
return filelist; | |
}; |
$ 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); });
I just want to say that every time someone comes up with another solution to this problem it makes my day :)
wow.. been receiving notifications for this thing for 9 years!.. it's the most consistent item in my dev career
There are only 3 hard problems in computer science... cache invalidation, naming things, off by one errors, and directory walking,
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
TypeScript version with filters:
Vanilla JS version if you don't use TypeScript: