Created
July 12, 2017 08:22
-
-
Save black-black-cat/558e5419c45b67b6a8d1880ebfc00787 to your computer and use it in GitHub Desktop.
在 `base` 目录以及其后代目录中查找匹配 `pattern` 的文件;目录或文件为 `except` 时,除外
This file contains hidden or 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
var path = require('path') | |
var fs = require('fs') | |
let pattern | |
let except | |
if (process.argv.length == 3) pattern = toRE(process.argv[2]) | |
if (process.argv.length == 4) { | |
pattern = toRE(process.argv[2]) | |
except = toRE(process.argv[3]) | |
} | |
function toRE(str) { | |
return new RegExp(str) | |
} | |
/** | |
* 在 `base` 目录以及其后代目录中查找匹配 `pattern` 的文件;目录或文件为 `except` 时,除外 | |
* 类似 glob 的 **\/*.* | |
* | |
* @param {String} base 目录 | |
* @param {RegExp} pattern 匹配文件名的正则 | |
* @param {RegExp} except 查找时除外的目录和文件 | |
*/ | |
function getAllFiles(base, pattern, except) { | |
base = base || path.resolve(__dirname, './') | |
except = except || /node_modules/ | |
let arr = [] | |
let files = fs.readdirSync(base) | |
files.forEach(function (file) { | |
if (except.test(file)) { | |
return | |
} | |
let pathname = path.join(base, file) | |
let stat = fs.lstatSync(pathname) | |
if (stat.isDirectory()) { | |
arr = arr.concat(getAllFiles(pathname, pattern)) | |
} else { | |
pattern.test(file) && arr.push(pathname) | |
} | |
}) | |
console.log(arr.length) | |
return arr | |
} | |
console.log(getAllFiles(null, pattern || /index/, except)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment