Skip to content

Instantly share code, notes, and snippets.

@rkaneko
Created September 6, 2017 02:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rkaneko/f0030ec1c6efe8b4958c340690139dc5 to your computer and use it in GitHub Desktop.
Save rkaneko/f0030ec1c6efe8b4958c340690139dc5 to your computer and use it in GitHub Desktop.
Node.js find files recursively
const assert = require("assert");
const fs = require("fs");
const path = require("path");
function findFilesRecursively(pathToDir) {
assert(typeof pathToDir === "string");
return fs.readdirSync(pathToDir).map(filename => {
const fullpath = path.join(pathToDir, filename);
if (isFile(fullpath)) {
return [fullpath];
} else if (isDirectory(fullpath)) {
return findFilesRecursively(fullpath);
}
return [];
}).reduce((files, current) =>
files.concat(current)
, []);
}
function isDirectory(pathToDir) {
assert(typeof pathToDir === "string");
try {
const stats = fs.statSync(pathToDir);
return stats.isDirectory();
} catch (err) {
return false;
}
}
function isFile(pathToFile) {
assert(typeof pathToFile === "string");
try {
const stats = fs.statSync(pathToFile);
return stats.isFile();
} catch (err) {
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment