Skip to content

Instantly share code, notes, and snippets.

@AkatQuas
Created September 24, 2019 11:10
Show Gist options
  • Save AkatQuas/56c6e2beb1ba912177e2863e5b58e204 to your computer and use it in GitHub Desktop.
Save AkatQuas/56c6e2beb1ba912177e2863e5b58e204 to your computer and use it in GitHub Desktop.
walk through a directory recursively, return all the files, filter supported
const fse = require('fs-extra');
const path = require('path');
const isNotDot = (filepath) => {
const REG = /^\..+/i;
return !REG.test(filepath);
};
/**
* calculate the relative path from `start` to `end`
* @param {String} start starting filepath
* @param {String} end ending filepath
* @returns {String}
*/
function relativePath(start, end) {
return path.relative(start, end);
}
/**
* walk a directory to get a flatterned array of files
* @param {string} dir The directory path
* @param {{filter: Function, skipDot: boolean}} p the relative path origin
* @returns {Array<{ purename, fullpath }>}
*/
function walk(dir, opt) {
let children = fse.readdirSync(dir);
const skipDot = opt.skipDot || true;
if (skipDot) {
children = children.filter(isNotDot);
}
if (opt.filter) {
children = children.filter(opt.filter);
}
let res = [];
children.forEach(f => {
const filepath = path.resolve(dir, f);
const stat = fse.statSync(filepath);
if (stat.isFile()) {
res.push({
purename: path.basename(filepath),
fullpath: filepath,
});
} else if (stat.isDirectory()) {
res = res.concat(walk(filepath, opt));
}
});
return res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment