Home > Software engineering >  Return directory file structure in Node JS
Return directory file structure in Node JS

Time:10-11

I'm trying to return a file structure from filesystem to present as "directory listing" if no index.html file is found in a webserver.

I have a function that traverse the directory and add the levels to an array

function getAllFiles(dirPath){
    var accPath = [];
    fs.readdirSync(dirPath).forEach(function(file) {
    let filepath = path.join(dirPath , file);
    let stat= fs.statSync(filepath);
    if (stat.isDirectory()) {            
      getAllFiles(filepath);
    } else {
          accPath.push(filepath);                  
    } 
}); 
accPath.forEach(elm => {
    // to check that I have traversed directory
    console.log(elm);
})  
return accPath; // returning the directory array 
}

I use it in like this:

var dirStructure = [];
dirStructure = getAllFiles(filePath);

   console.log("noOfFiles " dirStructure.length);
   dirStructure.forEach(lmnt => {
        console.log(lmnt);
   })

the result is that "getAllFiles" lists

public\css\bootstrap.min.css
public\js\bootstrap.min.js
public\js\jquery-3.3.1.slim.min.js
public\js\popper.min.js
public\index2.html

But I only get one element form the "dirStructure" array

"noOfFiles 1"
public\index2.html

CodePudding user response:

As I said in the comments, you never do anything with the recursive call

I suggest pushing it into accPath like accPath.push(...getAllFiles(filepath))

const fs = require('fs')
const path = require('path')

function getAllFiles(dirPath) {
  const accPath = [];
  fs.readdirSync(dirPath).forEach(file => {
    const filepath = path.join(dirPath, file);
    const stat = fs.statSync(filepath);
    if (stat.isDirectory()) {
      // you have to use the data returned from getAllFiles
      accPath.push(...getAllFiles(filepath));
    } else {
      accPath.push(filepath);
    }
  });

  return accPath;
}
  • Related