Convert a directory structure in the filesystem to JSON with Node.js Convert a directory structure in the filesystem to JSON with Node.js javascript javascript

Convert a directory structure in the filesystem to JSON with Node.js


Here's a sketch. Error handling is left as an exercise for the reader.

var fs = require('fs'),    path = require('path')function dirTree(filename) {    var stats = fs.lstatSync(filename),        info = {            path: filename,            name: path.basename(filename)        };    if (stats.isDirectory()) {        info.type = "folder";        info.children = fs.readdirSync(filename).map(function(child) {            return dirTree(filename + '/' + child);        });    } else {        // Assuming it's a file. In real life it could be a symlink or        // something else!        info.type = "file";    }    return info;}if (module.parent == undefined) {    // node dirTree.js ~/foo/bar    var util = require('util');    console.log(util.inspect(dirTree(process.argv[2]), false, null));}


there's an NPM Module for it

https://www.npmjs.com/package/directory-tree

Creates an object representing a directory tree.

From:

photos├── summer│   └── june│       └── windsurf.jpg└── winter    └── january        ├── ski.png        └── snowboard.jpg

To:

{  "path": "",  "name": "photos",  "type": "directory",  "children": [    {      "path": "summer",      "name": "summer",      "type": "directory",      "children": [        {          "path": "summer/june",          "name": "june",          "type": "directory",          "children": [            {              "path": "summer/june/windsurf.jpg",              "name": "windsurf.jpg",              "type": "file"            }          ]        }      ]    },    {      "path": "winter",      "name": "winter",      "type": "directory",      "children": [        {          "path": "winter/january",          "name": "january",          "type": "directory",          "children": [            {              "path": "winter/january/ski.png",              "name": "ski.png",              "type": "file"            },            {              "path": "winter/january/snowboard.jpg",              "name": "snowboard.jpg",              "type": "file"            }          ]        }      ]    }  ]}

Usage

var tree = directoryTree('/some/path');

And you can also filter by extensions:

var filteredTree = directoryTree('/some/path', ['.jpg', '.png']);


The accepted answer works, but it is synchronous and will deeply hurt your performance, especially for large directory trees.
I highly encourage you to use the following asynchronous solution, it is both faster and non-blocking.
Based on the parallel solution here.

var fs = require('fs');var path = require('path');var diretoryTreeToObj = function(dir, done) {    var results = [];    fs.readdir(dir, function(err, list) {        if (err)            return done(err);        var pending = list.length;        if (!pending)            return done(null, {name: path.basename(dir), type: 'folder', children: results});        list.forEach(function(file) {            file = path.resolve(dir, file);            fs.stat(file, function(err, stat) {                if (stat && stat.isDirectory()) {                    diretoryTreeToObj(file, function(err, res) {                        results.push({                            name: path.basename(file),                            type: 'folder',                            children: res                        });                        if (!--pending)                            done(null, results);                    });                }                else {                    results.push({                        type: 'file',                        name: path.basename(file)                    });                    if (!--pending)                        done(null, results);                }            });        });    });};

Example usage:

var dirTree = ('/path/to/dir');diretoryTreeToObj(dirTree, function(err, res){    if(err)        console.error(err);    console.log(JSON.stringify(res));});