fs.readdirSync,如何获取路径中的子文件夹?


如何

获取子文件夹?

路径距离/文档/:

  • 2006/Art1
  • 2006/艺术2
  • 2008/艺术1
  • 离线
  • 测试
const distPath = 'dist/docs/';
function getDirectories(distPath) {
return fs.readdirSync(distPath).filter(function (file) {
return fs.statSync(distPath + '/' + file).isDirectory();
}).filter(function (distPath) {
return distPath != 'test' && distPath != 'offline';
});
}
let articlePath = getDirectories(distPath);

意外

"2006"、"2006"、"2008">

预期

"2006/艺术1"、">

2006/艺术2"、"2008/艺术1">

fs.readdirSync只读取一个目录的内容;如果你发现一个条目是一个子目录,你需要读取给定子目录的内容,你也需要在子目录上调用fs.readdirSync

看来你需要一些递归的东西。

function deepGetDirectories(distPath) {
return fs.readdirSync(distPath).filter(function (file) {
return fs.statSync(distPath + '/' + file).isDirectory();
}).reduce(function(all, subDir) {
return [...all, ...fs.readdirSync(distPath + '/' + subDir).map(e => subDir + '/' + e)]
}, []);
}

感谢丹尼尔·里奇的回答!

function getDirectories(distPath) {
return fs.readdirSync(distPath).filter(function (file) {
return fs.statSync(distPath + '/' + file).isDirectory();
}).filter(function (distPath) {
return distPath != 'autoren' && distPath != 'offline';
}).reduce(function (all, subDir) {
return [...all, ...fs.readdirSync(distPath + '/' + subDir).map(e => subDir + '/' + e)]
}, []).filter(function (file) {
return fs.statSync(distPath + '/' + file).isDirectory();
});
}
let articlePath = getDirectories(distPath);

我使用了他的代码建议:

.reduce(function (all, subDir) {
return [...all, ...fs.readdirSync(distPath + '/' + subDir).map(e => subDir + '/' + e)]
}, []).filter(function (file) {
return fs.statSync(distPath + '/' + file).isDirectory();
});

最新更新