I have a file structure like this:
root
|_ fruits
|___ apple
|______images
|________ apple001.jpg
|________ apple002.jpg
|_ animals
|___ cat
|______images
|________ cat001.jpg
|________ cat002.jpg
I would like to, using Javascript and Node.js, listen to this root directory and all sub directories and create a JSON which mirrors this directory structure, each node contains type, name, path, and children:
data = [
{
type: "folder",
name: "animals",
path: "/animals",
children: [
{
type: "folder",
name: "cat",
path: "/animals/cat",
children: [
{
type: "folder",
name: "images",
path: "/animals/cat/images",
children: [
{
type: "file",
name: "cat001.jpg",
path: "/animals/cat/images/cat001.jpg"
}, {
type: "file",
name: "cat001.jpg",
path: "/animals/cat/images/cat002.jpg"
}
]
}
]
}
]
}
];
Here's a coffeescript JSON:
data =
[
type: "folder"
name: "animals"
path: "/animals"
children :
[
type: "folder"
name: "cat"
path: "/animals/cat"
children:
[
type: "folder"
name: "images"
path: "/animals/cat/images"
children:
[
type: "file"
name: "cat001.jpg"
path: "/animals/cat/images/cat001.jpg"
,
type: "file"
name: "cat001.jpg"
path: "/animals/cat/images/cat002.jpg"
]
]
]
]
how to get this json data format in django views?(python)
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));
}
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
You can use the code from this project but you should adapt the code to your needs:
https://github.com/NHQ/Node-FileUtils/blob/master/src/file-utils.js#L511-L593
From:
a
|- b
| |- c
| | |- c1.txt
| |
| |- b1.txt
| |- b2.txt
|
|- d
| |
|
|- a1.txt
|- a2.txt
To:
{
b: {
"b1.txt": "a/b/b1.txt",
"b2.txt": "a/b/b2.txt",
c: {
"c1.txt": "a/b/c/c1.txt"
}
},
d: {},
"a2.txt": "a/a2.txt",
"a1.txt": "a/a1.txt"
}
Doing:
new File ("a").list (function (error, files){
//files...
});
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));
});