Skip to content

CRSH your assets into tiny blocks!

by Qard on February 16th, 2012

Just now, I released version 0.2.0 of my nifty asset compression library, crsh. This new version comes with some majorly nifty stuff. Niftiest of them all is the new filter system. Similar to the middleware system used in connect/express, crsh now supports middleware to add support for any type of file you’d want to use! Here’s a quick sample of the csv-to-json filtering that I’ve got in the readme.

// Let's try a csv-to-json filter
Crsh.addFilter('csv', function () {
  var csv = require('csv')
  this.addType('json', 'csv')

  return function (data, next) {
    var pattern = /(?:^|,)("(?:[^"]+)*"|[^,]*)/g
      , lines = data.split("\n")
      , keys = lines.shift()
        .split(pattern)
        .map(function (key) {
          return key.toLowerCase()
        })
      , rows = lines.map(function (line) {
        var res = {}
        line.split(pattern).forEach(function (val, i) {
          if (keys[i]) {
            res[keys[i]] = val.replace(/"/g, '')
          }
        })
        return res
      })

    callback(null, JSON.stringify(rows))
  }
})

As you can see, crsh just got pretty darn flexible, thanks to filters. Next up is going to be output filters so you can specify how stuff gets joined. For example you could make a jsonp output filter to match the csv-to-json input filter above. The future is awesome. :D