-2

Here's what I'm trying to do, but just can't get my head around...

Say I have the following files and folders in my project, where 'Folder3' is a subfolder of 'Folder2':

- Folder1
   - File
   - File
   - File
- Folder2
   - File
   - File
   - File
   - Folder3
      - File
      - File
      - File

What I want is create an object that will mirror that structure:

var listing = {
   'Folder1' : {
      'File',
      'File',
      'File'
   }
   'Folder2' : {
      'File',
      'File',
      'File',
      'Folder3' : {
         'File',
         'File'
      }
   }
} 

I've looked at modules such as 'walk', but am not sure how to use them to create an object as described above. I've also looked at this question, but the top answer returns a one dimensional array, which isn't what I'm looking for.

Community
  • 1
  • 1
Simon
  • 29
  • 6
  • Use the `path` module (https://nodejs.org/api/path.html) and some recursion. Also, take a look at this SO question: http://stackoverflow.com/questions/5827612/node-js-fs-readdir-recursive-directory-search – cl3m Mar 25 '16 at 17:03
  • @cl3m Saw that question. The answer doesn't quite get what I'm looking for. It returns a one dimensional array. e.g. a file in Folder3 would be described with the string: 'Folder2/Folder3/File'. – Simon Mar 25 '16 at 17:12
  • see https://gist.github.com/Cl3MM/1a7aaafe1fdcd43ccd1b You might need to tweak it a little bit. – cl3m Mar 25 '16 at 18:09
  • by the way, your object structure is not valid. It should look like: `{folder1: [file1, file2, {folder2: [file1, file2, {folder3: [file1]}]}]}` – cl3m Mar 25 '16 at 18:15

1 Answers1

0

No dependency (other than node packages itself) working recursive directory traversal:

    var fs = require('fs');
    function readDirs(path, depth) {
        var fileIdentificator = '##file##';
        function readRecursive(pathsObject, path, depthCount) {
            if (depthCount == 0)
                return pathsObject;
            var files = fs.readdirSync(path);
            for (var fileIndex in files) {
                var file = files[fileIndex];
                pathsObject[file] = fileIdentificator;
                var currentPath = path + '/' + file;
                if( fs.lstatSync(currentPath).isDirectory()){
                 readRecursive( pathsObject[file] = {}, currentPath, depthCount-1 );
                }
            }
            return pathsObject;
        }
        return readRecursive({}, path, depth);
    }
    module.exports = readDirs;

//the output will be like this
    {
        a: {
            'a-a': {},
            'a-b': {},
            'a-c': {}
        },
        b: {
            'b-a': {},
            'b-b': {}
        },
        c: {
            'c-file.txt': '##file##'
        },
        d: {
            'd-file.txt': '##file##'
        },
        'root-file.txt': '##file##'
    }