Created
July 2, 2014 17:36
-
-
Save tkambler/fc2e44df387286c4ac07 to your computer and use it in GitHub Desktop.
Tracking file changes within Vagrant for real-time Browserify compilation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var async = require('async'), | |
glob = require('glob'), | |
browserify = require('browserify'), | |
_ = require('underscore'), | |
fs = require('fs'), | |
scriptBytes = 0, | |
compiled; | |
var getTotalBytes = function(patterns, cb) { | |
var tasks = [], | |
totalSize = 0; | |
_.each(patterns, function(pattern) { | |
tasks.push(function(cb) { | |
glob(pattern, function(err, scripts) { | |
if (err) { | |
return cb(err); | |
} | |
var counter = 0; | |
_.each(scripts, function(script) { | |
fs.stat(script, function(err, stats) { | |
if (err) { | |
return cb(err); | |
} | |
totalSize += stats.size; | |
counter++; | |
if (counter === scripts.length) { | |
return cb(null); | |
} | |
}); | |
}); | |
}); | |
}); | |
}); | |
async.series(tasks, function(err, result) { | |
if (err) { | |
return cb(err); | |
} | |
return cb(null, totalSize); | |
}); | |
}; | |
app.get('/api/js/app', function(req, res) { | |
var compile = function() { | |
res.set({ | |
'Content-Type': 'application/x-javascript' | |
}); | |
var b = browserify({ | |
'basedir': '/opt/app/app/scripts', | |
'commondir': '/opt/app/app/scripts' | |
}); | |
b.transform('brfs'); | |
b.transform('aliasify'); | |
b.add('./app.js'); | |
var bundle = b.bundle(), | |
contents = ''; | |
bundle.on('data', function(data) { | |
data = data.toString(); | |
contents += data; | |
}); | |
bundle.on('end', function() { | |
compiled = contents; | |
res.send(contents); | |
}); | |
}; | |
getTotalBytes([ | |
'/opt/app/bower_components/**/*.js', | |
'/opt/app/app/scripts/**/*.js' | |
], function(err, bytes) { | |
if (scriptBytes === bytes) { | |
res.send(compiled); | |
} else { | |
scriptBytes = bytes; | |
compile(); | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment