Skip to content

Instantly share code, notes, and snippets.

@brookjordan
Last active August 26, 2020 14:18
Show Gist options
  • Save brookjordan/6e9cd942b90c948f67fb3b5d62953565 to your computer and use it in GitHub Desktop.
Save brookjordan/6e9cd942b90c948f67fb3b5d62953565 to your computer and use it in GitHub Desktop.
Get all files from within a given directory using Node.js
// To log the results:
//
// getFiles(__dirname, { ignore: ['node_modules'] })
// .then(files => console.log(
// files
// .flat(Infinity)
// .filter(( Oo) => (Oo ))
// ));
// Available options:
// - ignore[] => circuit break at given files / directories
// - only[] => only include files matching filenames in this list
// - relative => emit paths relative to the inital directory
// - verbose => log errors and skipped files
const fs = require("fs");
const path = require("path");
const { promisify } = require("util");
const readdir = promisify(fs.readdir);
const getStat = promisify(fs.stat);
module.exports = getFiles;
async function getFiles(dir, o, initDirLength) {
dir || (dir = __dirname);
o || (o = {});
initDirLength || (initDirLength = dir.length);
try {
return await Promise.all(
(await readdir(dir)).map(async (file) => {
if (!file) {
if (o.verbose) {
console.log(`Missing file path under: ${dir}`);
}
return undefined;
}
const filePath = path.resolve(dir, file);
if (
o.ignore
&& o.ignore.includes(file)
) {
if (o.verbose) {
console.log(`Ignored: ${filePath}`);
}
return undefined;
}
if (
!o.includeHidden
&& file.startsWith(".")
) {
if (o.verbose) {
console.log(`Ignored hidden file: ${filePath}`);
}
return undefined;
}
const stat = await getStat(filePath);
if (stat && stat.isDirectory()) {
return await getFiles(filePath, o, initDirLength);
}
if (
!o.only
|| o.only.length === 0
|| o.only.includes(file)
) {
return o.relative
? filePath.slice(initDirLength + 1)
: filePath;
}
})
);
} catch (error) {
if (o.verbose) {
console.log(`Error reading: ${dir}`);
}
return undefined;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment