Skip to content

Instantly share code, notes, and snippets.

@bloatfan
Created November 22, 2016 13:31
Show Gist options
  • Save bloatfan/c53bf6eaf28136508abe119bcfd23fa6 to your computer and use it in GitHub Desktop.
Save bloatfan/c53bf6eaf28136508abe119bcfd23fa6 to your computer and use it in GitHub Desktop.
nodejs 遍历目录 返回目录项数组
function iteratorDir(dir, recursive) {
// 去除尾部的'/'字符
if (dir[dir.length - 1] == '/') {
dir = dir.substring(0, dir.length - 1);
}
var dirList = [];
var items = fs.readdirSync(dir);
items.forEach((item, index) => {
var path = dir + '/' + item;
var stat = fs.statSync(path);
if (stat.isFile()) {
dirList.push(path);
} else if (stat.isDirectory()) {
if (recursive) {
var subDirList = iteratorDir(path, recursive);
dirList = dirList.concat(subDirList);
} else {
path = path + '/';
dirList.push(path);
}
}
});
return dirList;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment