1

I am trying to take a folder structure and turn it into a JSON with this type of format:

.
├── Folder
│   ├── Image.png
│   └── Image_1.png
└── Folder2
    ├── Image.png
    └── Image_1.png

With a structure like this:

{
  "Folder": ["Image.png", "Image_1.png"],
  "Folder2": ["Image.png", "Image_1.png"]
}

Thanks. Is something like this possible?

Edit: This is what I have started with but the recursion is breaking when trying to drill down into folders within folders

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

var structure = {};

function findFiles(folder) {
    fs.readdir(folder, (err, files) => {
        files.forEach(file => {
            console.log(file);
            if(fs.lstatSync(__dirname + "/" + file).isDirectory()){
                console.log(folder)
                findFiles(folder + "/" + file);
            }
        });
    })
}

findFiles(__dirname)
Bitswazsky
  • 4,242
  • 3
  • 29
  • 58
Jeff
  • 353
  • 3
  • 17
  • 1
    It is possible. Maybe take a crack at it first? Start with the 'fs' library. Nice chance to use your recursion skills. – Jim B. Nov 01 '18 at 22:06
  • Well I'm a little stumped. I tried using fs.readdir, but not sure how to tell if it's a file or folder, and then how to know when to stop going deep down a path. – Jeff Nov 01 '18 at 22:16
  • @Jeff peruse the [documentation](https://nodejs.org/api/fs.html), and give it a try. Then post your attempt and what, specifically, does not work about it. – Alex Wayne Nov 01 '18 at 22:23
  • Well I have been going through it and getting stuck trying to find folders within folders. I added some code of where I am at. – Jeff Nov 01 '18 at 23:57
  • See my recent answer to a similar question: https://stackoverflow.com/a/52939775/4632627 – Richard Dunn Nov 02 '18 at 00:47
  • How do you want nested folders to be represented? – Jim B. Nov 02 '18 at 03:09

1 Answers1

1

Interesting problem. Here's my solution, using sync functions. The output JSON will contain an array of objects that can be either strings (for file names) or objects (for directories).

Code (live):

var fs = require('fs'), path = require('path'), util = require('util');

var dirToJSON = function(dir, done) {
  var results = [];

  function recWalk(d, res) {
    var list = fs.readdirSync(d);
    list.forEach((name) => {
      var tempResults = [];
      var file = path.resolve(d, name);
      var stat = fs.statSync(file);
      if (stat && stat.isDirectory()) {
        recWalk(file, tempResults);
        var obj = {};
        obj[name] = tempResults;
        res.push(obj);
      } else {
        res.push(name);
      }
    });
  }

  try {
    recWalk(dir, results);
    done(null, results);
  } catch(err) {
    done(err);
  }
};

dirToJSON("/home/", function(err, results) {
  if (err) console.log(err);
  else console.log(util.inspect(results, {showHidden: false, depth: null}));
});

Output:

[ { node: [ '.bash_logout', '.bashrc', '.profile' ] },
  { runner: 
     [ '.bash_logout',
       '.bashrc',
       '.profile',
       'config.json',
       'index.js',
       { node_modules: [] },
       'test.js' ] } ]

Note that I'm printing results with util.inspect to allow infinite depth for objects, but you can also do JSON.stringify(results)

mihai
  • 37,072
  • 9
  • 60
  • 86