Skip to content

Instantly share code, notes, and snippets.

@peterbe
Last active August 15, 2019 13:31
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save peterbe/48e4a12d60c339cc6acbfe2bb6c7bbeb to your computer and use it in GitHub Desktop.
import fs from "fs";
import path from "path";
// https://www.npmjs.com/package/glob
import glob from "glob";
/** Given an array of "things" return all distinct .json files.
*
* Note that these "things" can be a directory, a file path, or a
* pattern.
* Only if each thing is a directory do we search for *.json files
* in there recursively.
*/
function expandFiles(directoriesPatternsOrFiles) {
function findFiles(directory) {
const found = glob.sync(path.join(directory, "*.json"));
fs.readdirSync(directory, { withFileTypes: true })
.filter(dirent => dirent.isDirectory())
.map(dirent => path.join(directory, dirent.name))
.map(findFiles)
.forEach(files => found.push(...files));
return found;
}
const filePaths = [];
directoriesPatternsOrFiles.forEach(thing => {
let files = [];
if (thing.includes("*")) {
// It's a pattern!
files = glob.sync(thing);
} else {
const lstat = fs.lstatSync(thing);
if (lstat.isDirectory()) {
files = findFiles(thing);
} else if (lstat.isFile()) {
files = [thing];
} else {
throw new Error(`${thing} is neither file nor directory`);
}
}
files.forEach(p => filePaths.includes(p) || filePaths.push(p));
});
return filePaths;
}
@peterbe
Copy link
Author

peterbe commented Aug 15, 2019

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