1 | /* |
---|
2 | * grunt-contrib-watch |
---|
3 | * http://gruntjs.com/ |
---|
4 | * |
---|
5 | * Copyright (c) 2014 "Cowboy" Ben Alman, contributors |
---|
6 | * Licensed under the MIT license. |
---|
7 | */ |
---|
8 | |
---|
9 | 'use strict'; |
---|
10 | |
---|
11 | var tinylr = require('tiny-lr-fork'); |
---|
12 | var _ = require('lodash'); |
---|
13 | |
---|
14 | // Holds the servers out of scope in case watch is reloaded |
---|
15 | var servers = Object.create(null); |
---|
16 | |
---|
17 | module.exports = function(grunt) { |
---|
18 | |
---|
19 | var defaults = { port: 35729 }; |
---|
20 | |
---|
21 | function LR(options) { |
---|
22 | if (options === true) { |
---|
23 | options = defaults; |
---|
24 | } else if (typeof options === 'number') { |
---|
25 | options = {port: options}; |
---|
26 | } else { |
---|
27 | options = _.defaults(options, defaults); |
---|
28 | } |
---|
29 | if (servers[options.port]) { |
---|
30 | this.server = servers[options.port]; |
---|
31 | } else { |
---|
32 | this.server = tinylr(options); |
---|
33 | this.server.server.removeAllListeners('error'); |
---|
34 | this.server.server.on('error', function(err) { |
---|
35 | if (err.code === 'EADDRINUSE') { |
---|
36 | grunt.fatal('Port ' + options.port + ' is already in use by another process.'); |
---|
37 | } else { |
---|
38 | grunt.fatal(err); |
---|
39 | } |
---|
40 | process.exit(1); |
---|
41 | }); |
---|
42 | this.server.listen(options.port, function(err) { |
---|
43 | if (err) { return grunt.fatal(err); } |
---|
44 | grunt.log.verbose.writeln('Live reload server started on port: ' + options.port); |
---|
45 | }); |
---|
46 | servers[options.port] = this.server; |
---|
47 | } |
---|
48 | } |
---|
49 | |
---|
50 | LR.prototype.trigger = function(files) { |
---|
51 | grunt.log.verbose.writeln('Live reloading ' + grunt.log.wordlist(files) + '...'); |
---|
52 | this.server.changed({body:{files:files}}); |
---|
53 | }; |
---|
54 | |
---|
55 | return function(options) { |
---|
56 | return new LR(options); |
---|
57 | }; |
---|
58 | }; |
---|