我正在递归地移动大型目录树(从100,000到1,000,000个对象)并且需要将每个文件或目录添加到深层嵌套对象。
我们假设我有像
这样的文件路径/path/to/file1
/path/to/file2
...
/pathX/file1000000
我需要根据它们创建以下嵌套对象:
{
"name": "/",
"value": 300,
"children": [
{
"name": "/pathX",
"value": 100,
"children": [
{
"name": "/pathX/file1000000",
"value": 100
}
},
{
"name": "/path",
"value": 200,
"children": [
{
"name": "/path/to",
"value": 200,
"children": [
{
"name": "/path/to/file1",
"value": 100
},
{
"name": "/path/to/file2",
"value": 100
}
]
}
]
}
]
}
value
是文件大小或嵌套文件大小的总和。为了简单起见,我们假设它等于100
,file1
和file2
的{{1}}。
我能够为一个文件构建嵌套对象,但在为具有不同路径的许多文件构建它时遇到问题:
fileN
答案 0 :(得分:1)
你去:)
function buildTree(pathes, getValueCB) {
var currentPath, lastPath, node, parent, map = {
"": {
children: []
}
},
stack = [""]
for (let path of pathes) {
let nodes = path.split("/");
for (let i = 0; i < nodes.length; i++) {
currentPath = "/" + nodes.slice(1, i + 1).join("/")
lastPath = stack[stack.length - 1]
parent = map[lastPath]
if (!map[currentPath]) {
node = {
name: currentPath,
value: getValueCB(currentPath),
children: []
}
parent.children.push(node);
map[currentPath] = node;
}
stack.push(currentPath)
}
stack = stack.slice(0, 1)
}
return map[""].children[0];
}
function getFileSizeSync() {
return 200
}
var tree = buildTree(["/path/to/file1", "/path/to/file2"], function(path) {
return getFileSizeSync(path)
})
console.log (tree)
&#13;
这里是递归计算大小的更新版本。 (我无法将其放入一个片段,这就是我离开旧片段的原因)
var fs = require('fs')
var Path = require ('path')
function calcSize (node) {
var children = node.children;
node.value = children.reduce (function (size, child) {
return size + child.value || reduceSize (child);
}, 0)
return node.value;
}
function getFileSizeSync(path) {
var size = fs.statSync(path).size
return size
}
function buildTree(pathes, getValueCB) {
var currentPath, lastPath, node, parent, map = {
"": {
children: []
}
},
stack = [""]
for (let path of pathes) {
let nodes = path.split(Path.sep);
for (let i = 0; i < nodes.length; i++) {
currentPath = Path.sep + nodes.slice(1, i + 1).join(Path.sep)
lastPath = stack[stack.length - 1]
parent = map[lastPath]
if (!map[currentPath]) {
node = {
name: currentPath,
value: getFileSizeSync(currentPath),
children: []
}
parent.children.push(node);
map[currentPath] = node;
}
stack.push(currentPath)
}
stack = stack.slice(0, 1)
}
calcSize (map[""])
return map[""].children[0];
}
var tree = buildTree(["/path/to/file1", "/path/to/file2"])
console.log (tree)