Skip to content

Commit

Permalink
fixes for livereload injection
Browse files Browse the repository at this point in the history
  • Loading branch information
Contra committed Jul 12, 2014
1 parent fd4ac06 commit d4da514
Showing 1 changed file with 14 additions and 23 deletions.
37 changes: 14 additions & 23 deletions lib/serve/createServer.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,36 +10,27 @@ module.exports = function (port, lrPort, open, next) {
var root = path.resolve(process.cwd());

var server = http.createServer(function(req, res) {
if ('GET' != req.method && 'HEAD' != req.method) {
res.writeHead(400, {'Content-type': 'text/plain'});
res.end('Method not supported');
return;
}

var path = url.parse(req.url).pathname;
var stream = send(req, path, {root: root});
var filePath = url.parse(req.url).pathname;
var streamer = send(req, filePath, {root: root});

// handle errors
stream.on('error', function error(err) {
streamer.once('error', function error(err) {
res.statusCode = err.status || 500;
res.end(err.message);
});

stream.on('directory', function(){
res.statusCode = 301;
res.setHeader('Location', req.url + '/index.html');
res.end();
// this is a hack
streamer.once('stream', function hookStream(realStream){
// if html, inject lr
if (path.extname(filePath).match(/\.htm(l)?$/)) {
var orig = realStream.pipe.bind(realStream);
realStream.pipe = function(newStream, opt) {
var replacer = rstream('</body>', getLivereloadTag(lrPort)+'</body>');
return orig(replacer).pipe(newStream);
};
}
});

// if html, inject lr
if (path.extname(path).match(/\.htm(l)?$/)) {
stream
.pipe(rstream('</body>', getLivereloadTag(lrPort)+'</body>'))
.pipe(res);
} else {
// stream file to response
stream.pipe(res);
}
streamer.pipe(res);
});

// find available http port
Expand Down

0 comments on commit d4da514

Please sign in to comment.