Created
August 28, 2013 21:16
-
-
Save chug2k/6371408 to your computer and use it in GitHub Desktop.
How to get livereload working with large files (borrowed from: https://github.com/getfatday/grunt-contrib-livereload/blob/dd405184557cbd8ffdcaa400c50c13436f7d6d27/lib/utils.js)
This file contains 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
module.exports = function liveReload(opt) { | |
var opt = opt || {}; | |
var port = opt.port || 35729; | |
var excludeList = opt.excludeList || ['.woff', '.js', '.css', '.ico']; | |
function getSnippet() { | |
/*jshint quotmark:false */ | |
var snippet = [ | |
"<!-- livereload script -->", | |
"<script type=\"text/javascript\">document.write('<script src=\"http://'", | |
" + (location.host || 'localhost').split(':')[0]", | |
" + ':" + port + "/livereload.js?snipver=1\" type=\"text/javascript\"><\\/script>')", | |
"</script>", | |
"" | |
].join('\n'); | |
return snippet; | |
}; | |
function bodyExists(body) { | |
if (!body) return false; | |
return (~body.lastIndexOf("</body>")); | |
} | |
function snippetExists(body) { | |
if (!body) return true; | |
return (~body.lastIndexOf("/livereload.js?snipver=1")); | |
} | |
function acceptsHtmlExplicit(req) { | |
var accept = req.headers["accept"]; | |
if (!accept) return false; | |
return (~accept.indexOf("html")); | |
} | |
function isExcluded(req) { | |
var url = req.url; | |
var excluded = false; | |
if (!url) return true; | |
excludeList.forEach(function(exclude) { | |
if (~url.indexOf(exclude)) { | |
excluded = true; | |
} | |
}); | |
return excluded; | |
} | |
return function(req, res, next) { | |
var writeHead = res.writeHead; | |
var write = res.write; | |
var end = res.end; | |
if (!acceptsHtmlExplicit(req) || isExcluded(req)) { | |
return next(); | |
} | |
res.push = function(chunk) { | |
res.data = (res.data || '') + chunk; | |
}; | |
// Bypass write until end | |
var inject = res.write = function (string, encoding) { | |
if ( string !== undefined ) { | |
var body = string instanceof Buffer ? string.toString(encoding) : string; | |
res.push(body.replace(/<\/body>/, function (w) { | |
return getSnippet() + w; | |
})); | |
} | |
return true; | |
}; | |
// Prevent headers from being finalized | |
res.writeHead = function() { }; | |
// Write everything at the end | |
res.end = function (string, encoding) { | |
inject(string, encoding); | |
// Restore writeHead | |
res.writeHead = writeHead; | |
if (res.data !== undefined ) { | |
if (!res._header) { | |
res.setHeader('content-length', Buffer.byteLength(res.data, encoding)); | |
} | |
end.call(res, res.data, encoding); | |
} | |
}; | |
next(); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment