Skip to content

Instantly share code, notes, and snippets.

@jsdf
Last active August 29, 2015 14:14
Show Gist options
  • Save jsdf/fd4665e11e63397c84e5 to your computer and use it in GitHub Desktop.
Save jsdf/fd4665e11e63397c84e5 to your computer and use it in GitHub Desktop.
poor man's sprockets (async)
#!/usr/bin/env node
var crypto = require('crypto')
var path = require('path')
var fs = require('fs')
var Promise = require('bluebird')
Promise.promisifyAll(fs)
function hash(input, algorithm, encoding) {
return crypto
.createHash(algorithm || 'md5')
.update(input, 'utf8')
.digest(encoding || 'hex')
}
var assetMap = {}
var assetMapFileDir = null
Promise.map(process.argv.slice(2), function(filearg) {
var file = path.relative(process.cwd(), filearg)
var fileDir = path.dirname(file)
var fileExt = path.extname(file)
if (!assetMapFileDir) assetMapFileDir = fileDir
return fs.readFileAsync(file)
.then(function(fileContents) {
var digest = hash(fileContents)
assetMap[file] = path.join(fileDir, path.basename(file, fileExt)+'-'+digest.slice(0, 8)+fileExt)
return fs.writeFileAsync(assetMap[file], fileContents)
})
})
.then(function() {
return fs.writeFileAsync(
path.join(assetMapFileDir, 'assets.json'),
JSON.stringify(assetMap, null, 2)
)
})
.then(function() {
process.exit(0)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment