Last active
August 15, 2019 13:31
Star
You must be signed in to star a gist
This file contains 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
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For blog post: https://www.peterbe.com/plog/function-expandfiles