Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a folder structure from definitions on a json file

how can i create a folder structure using this json structure

{
  "europe": {
    "poland":{},
    "france":{},
    "spain":{},
    "greece":{},
    "UK":{},
    "germany":"txt"
  },
  "Asia": {
    "india":"xml"
  },
  "Africa":null
}

in such a way that

  1. properties with object values become folders
  2. properties with string values are files and their values represent their extensions
  3. properties with null values are files with no extension
  4. nested objects become nested folders

anyone know how to do this in nodejs?

like image 426
shanks Avatar asked Feb 22 '26 07:02

shanks


1 Answers

You'll have to recursively iterate and create folders and files.

Not tested, but something like this should be close

var fs  = require('fs');
var obj = {
    "europe": {
        "poland": {},
        "france": {},
        "spain": {},
        "greece": {},
        "UK": {},
        "germany": "txt"
    },
    "Asia": {
        "india": "xml"
    },
    "Africa": null
};

(function create(folder, o) {
    for (var key in o) {
        if ( typeof o[key] === 'object' && o[key] !== null) {
            fs.mkdir(folder + key, function() {
                if (Object.keys(o[key]).length) {
                    create(folder + key + '/', o[key]);
                }
            });
        } else {
            fs.writeFile(folder + key + (o[key] === null ? '' : '.' + o[key]));
        }
    }
})('/', obj);

FIDDLE

like image 122
adeneo Avatar answered Feb 24 '26 20:02

adeneo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!