Created
September 6, 2017 02:43
-
-
Save rkaneko/f0030ec1c6efe8b4958c340690139dc5 to your computer and use it in GitHub Desktop.
Node.js find files recursively
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
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