3

how do I get the subfolders?

Path dist/docs/:

  • 2006/Art1
  • 2006/Art2
  • 2008/Art1
  • offline
  • test
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'

2 Answers 2

4

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)] }, []); } 
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.