Last active
September 12, 2017 20:48
-
-
Save xdesro/cc4567bc5d1f2d20fb3e62eee9984e18 to your computer and use it in GitHub Desktop.
A node.js function to find all files in a directory by given filter.
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 fs = require('fs'); | |
const path = require('path'); | |
function findFiles(startPath,filter,callback){ | |
if (!fs.existsSync(startPath)){ | |
console.log("Gosh, can't seem to find what you're looking for, my friend! Try a different startPath"); | |
return; | |
} | |
const files=fs.readdirSync(startPath); | |
for (let currentFilePath of files) { | |
const filename=path.join(startPath,currentFilePath); | |
const stat = fs.lstatSync(filename); | |
if (stat.isDirectory()){ | |
fromDir(filename,filter,callback); | |
} | |
else if (filter.test(filename)) callback(filename); | |
} | |
} | |
// Example: | |
// let collectedFiles = []; | |
// findFiles('.',/\.html$|\.shtml$/,filename => { | |
// collectedFiles.push(filename); | |
// }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment