Skip to content

Instantly share code, notes, and snippets.

@wallace7souza
Created August 10, 2017 02:17
Show Gist options
  • Save wallace7souza/843e1253848514aebcd52d8d19cf8b9b to your computer and use it in GitHub Desktop.
Save wallace7souza/843e1253848514aebcd52d8d19cf8b9b to your computer and use it in GitHub Desktop.
convert a directory structure in the filesystem to json with node-js
// Copied from
// https://stackoverflow.com/questions/11194287/convert-a-directory-structure-in-the-filesystem-to-json-with-node-js
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));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment