UNPKG

3.29 kBJavaScriptView Raw
1/**
2 * Created by rodey on 2016/8/19.
3 * 此文件用于服务器端实时监听文件变化
4 * 采用 Websocket 进行实时通信
5 */
6'use strict';
7
8const wsServer = require('ws').Server;
9const chokidar = require('chokidar');
10const extend = require('extend');
11
12const defaults = {
13 debug: false,
14 host: '127.0.0.1',
15 port: 8523,
16 paths: null,
17 liveDelay: 2000,
18 ignored: [/\\.git\//, /\\.svn\//, /\\.hg\//]
19};
20
21module.exports.LiveServer = (function() {
22 function LiveServer(options) {
23 this.options = extend(true, {}, defaults, options);
24 this.init();
25 }
26
27 LiveServer.prototype = {
28 init: function() {
29 this.socket = null;
30 this.watcher = null;
31 this.server = new wsServer(this.options);
32 this.server.on('connection', this.onConnection.bind(this));
33 return this.server.on('close', this.onClose.bind(this));
34 },
35
36 onConnection: function(socket) {
37 this.socket = socket;
38 this.socket.on('message', this.onMessage.bind(this));
39 return this.socket.on('error', this.onError.bind(this));
40 },
41
42 onMessage: function(message) {
43 return this.debug('Browser URL: ' + message);
44 },
45
46 onError: function(err) {
47 return this.debug('Error in client socket: ' + err);
48 },
49
50 onClose: function() {
51 return this.debug('Browser disconnected.');
52 },
53
54 /**
55 * 监听
56 * @param paths
57 * @returns {*}
58 */
59 watching: function(paths) {
60 paths = paths || this.options.paths;
61 this.options.paths = paths;
62 return (this.watcher = chokidar
63 .watch(paths, {
64 ignoreInitial: true,
65 ignored: this.options.ignored,
66 usePolling: this.options.usePolling
67 })
68 .on('add', this._filterRefresh.bind(this))
69 .on('change', this._filterRefresh.bind(this))
70 .on('unlink', this._filterRefresh.bind(this)));
71 },
72
73 unwatch: function(paths) {
74 paths = paths || this.options.paths;
75 this.options.paths = paths;
76 return this.watcher && this.watcher.unwatch(paths);
77 },
78
79 debug: function(str) {
80 if (this.options.debug) {
81 return console.log(str + '\n');
82 }
83 },
84
85 send: function(data) {
86 this.socket && this.socket.send(data);
87 },
88
89 _filterRefresh: function(filepath, event) {
90 let delayedRefresh;
91 return (delayedRefresh = setTimeout(
92 (function(_this) {
93 return function() {
94 clearTimeout(delayedRefresh);
95 return _this._refresh(filepath);
96 };
97 })(this),
98 this.options.liveDelay
99 ));
100 },
101
102 _refresh: function(filepath) {
103 this.debug('Refresh: ' + filepath);
104 this.send('<<<-----server reload----->>>');
105 }
106 };
107
108 return LiveServer;
109})();