Skip to content

Instantly share code, notes, and snippets.

@xdesro
Last active September 12, 2017 20:48
Show Gist options
  • Save xdesro/cc4567bc5d1f2d20fb3e62eee9984e18 to your computer and use it in GitHub Desktop.
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.
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