Skip to content

Instantly share code, notes, and snippets.

@tkambler
Created July 2, 2014 17:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tkambler/fc2e44df387286c4ac07 to your computer and use it in GitHub Desktop.
Save tkambler/fc2e44df387286c4ac07 to your computer and use it in GitHub Desktop.
Tracking file changes within Vagrant for real-time Browserify compilation
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