Created
November 22, 2016 13:31
-
-
Save bloatfan/c53bf6eaf28136508abe119bcfd23fa6 to your computer and use it in GitHub Desktop.
nodejs 遍历目录 返回目录项数组
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
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