Convert a directory structure in the filesystem to JSON with Node.js
My CS example (w/ express) based on Miika's solution:
fs = require 'fs' #file system module
path = require 'path' # file path module
# returns json tree of directory structure
tree = (root) ->
# clean trailing '/'(s)
root = root.replace /\/+$/ , ""
# extract tree ring if root exists
if fs.existsSync root
ring = fs.lstatSync root
else
return 'error: root does not exist'
# type agnostic info
info =
path: root
name: path.basename(root)
# dir
if ring.isDirectory()
info.type = 'folder'
# execute for each child and call tree recursively
info.children = fs.readdirSync(root) .map (child) ->
tree root + '/' + child
# file
else if ring.isFile()
info.type = 'file'
# link
else if ring.isSymbolicLink()
info.type = 'link'
# other
else
info.type = 'unknown'
# return tree
info
# error handling
handle = (e) ->
return 'uncaught exception...'
exports.index = (req, res) ->
try
res.send tree './test/'
catch e
res.send handle e
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']);
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));
}
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));
});