-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathutils.js
109 lines (89 loc) · 2.63 KB
/
utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
'use strict';
var Server = require('tiny-lr');
var path = require('path');
var url = require('url');
var utils = module.exports;
var port = 35729;
utils.startLRServer = function startLRServer(grunt, done) {
var _ = grunt.util._;
var _server;
var options = _.defaults(grunt.config('livereload') || {}, {
port: 35729
});
_server = new Server();
grunt.log.writeln('... Starting Livereload server on ' + options.port + ' ...');
port = options.port;
_server.listen(options.port, done);
return _server;
};
utils.getSnippet = function () {
/*jshint quotmark:false */
var snippet = [
"<!-- livereload snippet -->",
"<script>document.write('<script src=\"http://'",
" + (location.host || 'localhost').split(':')[0]",
" + ':" + port + "/livereload.js?snipver=1\"><\\/script>')",
"</script>",
""
].join('\n');
return snippet;
};
//
// This function returns a connect middleware that will insert a snippet
// of JavaScript needed to connect to the livereload server
//
// Usage:
// First require the needed module
// var lrSnippet = require('livereload/lib/utils').livereloadSnippet;
//
// Then in your grunt-contrib-connect config:
//
// server: {
// dist: {
// middleware: function() {
// return [lrSnippet, folderMount('dist')]
// }
// },
// test: {
// middleware: function() {
// return [lrSnippet(grunt), folderMount('dist')]
// }
// }
// }
utils.livereloadSnippet = function livereloadSnippet(req, res, next) {
var writeHead = res.writeHead;
var end = res.end;
var filepath = url.parse(req.url).pathname;
filepath = filepath.slice(-1) === '/' ? filepath + 'index.html' : filepath;
if (path.extname( filepath ) !== '.html' && res.send === undefined) {
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 utils.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();
};