I'm walking large directory tree recursively (from 100,000 to 1,000,000 objects) and need to add each file or directory to deeply nested object.
Let's assume I got file paths like
/path/to/file1
/path/to/file2
...
/pathX/file1000000
and I need to create following nested object based on them:
{
"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
}
]
}
]
}
]
}
The value is a file size or sum of nested file sizes. To keep things simple, let's assume its equal to 100 for file1, file2 and fileN.
I was able to build nested object for one file, but having issues with building it for many files with different paths:
const path = require('path')
const fs = require('fs')
let file = '/opt/bin/file1'
let size
fs.stat(file, (err, stats) => { size = stats.size })
let paths = file.split(path.sep)
let nameChild = file
let objChild = { "name" : nameChild, "value" : size }
let nameParent
let objParent
for (var i in paths) {
if (i==0) continue
nameParent = path.dirname(nameChild)
objParent = { "name" : nameParent, "value" : size, "children" : [ objChild ] }
nameChild = nameParent
objChild = objParent
}
console.log(JSON.stringify(objParent))