Jeff
Jeff

Reputation: 373

Folder structure to json

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)

Upvotes: 1

Views: 2777

Answers (1)

mihai
mihai

Reputation: 38573

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)

Upvotes: 1

Related Questions