Open zeke opened 10 years ago
This is quick and dirty (shouldn't be using readFileSync
, has terrible error-handling), but it's not actually a lot of code. Stir in async
or some promises and it should even be a little tighter:
var tree = {}
glob("svg/**/*.svg", function (er, names) {
// error handling
names.forEach(function (name) {
var p = name.split('/')
p.shift() // get rid of 'svg'
var basename = path.basename(p.pop(), ".svg")
var node = tree
while (p.length) {
var current = p.shift()
if (!(current in node)) node[current] = {}
node = node[current]
}
node[basename] = fs.readFileSync(name)
}
cb(null, JSON.stringify(tree))
}
I have a directory that looks like this:
And I want to end up with this:
There are million ways to do this, but I can't think of one that doesn't mean chopping up pathnames and manually assembling deep objects using something like steeltoe. Maybe @ceej or @bcoe or @rockbot or @othiym23 or @rebecca or @issacs or @seldo know of an elegant approach..
Here's how it works now for a flat directory of files: https://github.com/npm/graphics/blob/1e715dfef210968432b03df5cd25a8f15b89169a/lib/build.js