I have a file structure like this:
JavaScript
x
12
12
1
root
2
|_ fruits
3
|___ apple
4
|______images
5
|________ apple001.jpg
6
|________ apple002.jpg
7
|_ animals
8
|___ cat
9
|______images
10
|________ cat001.jpg
11
|________ cat002.jpg
12
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:
JavaScript
1
33
33
1
data = [
2
{
3
type: "folder",
4
name: "animals",
5
path: "/animals",
6
children: [
7
{
8
type: "folder",
9
name: "cat",
10
path: "/animals/cat",
11
children: [
12
{
13
type: "folder",
14
name: "images",
15
path: "/animals/cat/images",
16
children: [
17
{
18
type: "file",
19
name: "cat001.jpg",
20
path: "/animals/cat/images/cat001.jpg"
21
}, {
22
type: "file",
23
name: "cat001.jpg",
24
path: "/animals/cat/images/cat002.jpg"
25
}
26
]
27
}
28
]
29
}
30
]
31
}
32
];
33
Here’s a coffeescript JSON:
JavaScript
1
29
29
1
data =
2
[
3
type: "folder"
4
name: "animals"
5
path: "/animals"
6
children :
7
[
8
type: "folder"
9
name: "cat"
10
path: "/animals/cat"
11
children:
12
[
13
type: "folder"
14
name: "images"
15
path: "/animals/cat/images"
16
children:
17
[
18
type: "file"
19
name: "cat001.jpg"
20
path: "/animals/cat/images/cat001.jpg"
21
,
22
type: "file"
23
name: "cat001.jpg"
24
path: "/animals/cat/images/cat002.jpg"
25
]
26
]
27
]
28
]
29
how to get this json data format in django views?(python)
Advertisement
Answer
Here’s a sketch. Error handling is left as an exercise for the reader.
JavaScript
1
30
30
1
var fs = require('fs'),
2
path = require('path')
3
4
function dirTree(filename) {
5
var stats = fs.lstatSync(filename),
6
info = {
7
path: filename,
8
name: path.basename(filename)
9
};
10
11
if (stats.isDirectory()) {
12
info.type = "folder";
13
info.children = fs.readdirSync(filename).map(function(child) {
14
return dirTree(filename + '/' + child);
15
});
16
} else {
17
// Assuming it's a file. In real life it could be a symlink or
18
// something else!
19
info.type = "file";
20
}
21
22
return info;
23
}
24
25
if (module.parent == undefined) {
26
// node dirTree.js ~/foo/bar
27
var util = require('util');
28
console.log(util.inspect(dirTree(process.argv[2]), false, null));
29
}
30