Skip to content

Instantly share code, notes, and snippets.

@GingerBear
Last active August 29, 2015 14:23
Show Gist options
  • Save GingerBear/de01b810e7edf449271e to your computer and use it in GitHub Desktop.
Save GingerBear/de01b810e7edf449271e to your computer and use it in GitHub Desktop.
style watcher
// ------------------------------------------------------------------------
// In app.js (using connect-assets for assets pipeline)
// ------------------------------------------------------------------------
app.use(require('./style-watcher.js')(app));
// ------------------------------------------------------------------------
// style-watcher.js
// ------------------------------------------------------------------------
var chokidar = require('chokidar');
var socketIo = require('socket.io');
var colors = require('colors');
var fs = require('fs');
var cwd = process.cwd();
module.exports = function(app) {
var io = socketIo.listen(app.server)
var watcher = chokidar.watch(cwd + '/assets/css/'); // watch stylus file
var browserScript = fs.readFileSync(cwd + '/views/partials/style-watcher.hbs', {encoding: 'utf8'});
watcher.on('change', injectCSS);
function injectCSS(rawFileName) {
var fileName = rawFileName.replace(cwd, '');
console.log('Style Updated '.yellow + fileName);
io.emit('style-updated', fileName);
}
// inject client side script to html head
return function styleWatcherMiddleware(req, res, next) {
var oldSend = res.send;
res.send = function (status, data) {
if (typeof data !== 'undefined'
&& browserScript
&& data.indexOf
&& data.indexOf('</head>') > -1) {
data = data.replace('</head>', browserScript + '</head>');
}
return oldSend.call(this, status, data);
}
next();
};
};
// ------------------------------------------------------------------------
// style-watcher.hbs
// ------------------------------------------------------------------------
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.5/socket.io.min.js"></script>
<script>
var host = window.location.href.match(/https?:\/\/[^\/]+/).pop();
var socket = io(host);
socket.on('style-updated', function(fileName) {
console.log('Style updated on: ' + fileName);
$('link[href*="/assets/"][href*=".css"]').each(function() {
var $link = $(this);
var href = $link.attr('href').replace(/\?.*/, '');
href = href + '?t=' + (new Date()).getTime();
$link.replaceWith(
'<link rel="stylesheet" href="' + href + '">'
);
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment