Skip to content

Instantly share code, notes, and snippets.

@peterbe peterbe/expandFiles.js
Last active Aug 15, 2019

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

peterbe commented Aug 15, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.