Cem Firat
Cem Firat

Reputation: 410

fs.readdirSync, how do I get the subfolders in path?

how do I get the subfolders?

Path dist/docs/:

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

unexpected

'2006', '2006', '2008'

expected

'2006/Art1', '2006/Art2', '2008/Art1'

Upvotes: 2

Views: 2674

Answers (2)

Cem Firat
Cem Firat

Reputation: 410

Thanks Daniele Ricci for your Answer!

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

I used his code suggestion:

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

Upvotes: 2

Daniele Ricci
Daniele Ricci

Reputation: 15797

fs.readdirSync reads the content of only one directory; if you find an entry is a subdirectory and you need to read the content of given subdirectory, you need to call fs.readdirSync on the subdirectory as well.

It seems you need something recursive.

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

Upvotes: 3

Related Questions