提问者:小点点

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


路径Dist/Docs/:

  • 2006/ART1
  • 2006/ART2
  • 2008/ART1
  • 脱机
  • 测试
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/ART1”,“2006/ART2”,“2008/ART1”


共2个答案

匿名用户

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)]
    }, []);
}

匿名用户

谢谢Daniele Ricci的回答!

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();
  });