npm / graphics

All the npm SVGs stuffed into a JSON object
3 stars 6 forks source link

Create a nested tree of SVG files #1

Open zeke opened 10 years ago

zeke commented 10 years ago

I have a directory that looks like this:

svg
  maybe.svg
  npm
    logo.svg
  devicons
    foo.svg
    bar.svg

And I want to end up with this:

{
  maybe: "<svg>...</svg>",
  npm: {
    logo: "<svg>...</svg>"
  },
  devicons: {
    foo: "<svg>...</svg>",
    bar: "<svg>...</svg>"
  }
}

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

othiym23 commented 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))
}