UNPKG

2.98 kBJavaScriptView Raw
1/**
2 * Copyright 2013-2021 the PM2 project authors. All rights reserved.
3 * Use of this source code is governed by a license that
4 * can be found in the LICENSE file.
5 */
6var chokidar = require('chokidar');
7var util = require('util');
8var log = require('debug')('pm2:watch');
9
10module.exports = function ClusterMode(God) {
11 /**
12 * Watch folder for changes and restart
13 * @method watch
14 * @param {Object} pm2_env pm2 app environnement
15 * @return MemberExpression
16 */
17 God.watch = {};
18
19 God.watch._watchers = {};
20
21 God.watch.enable = function(pm2_env) {
22 if (God.watch._watchers[pm2_env.pm_id]) {
23 God.watch._watchers[pm2_env.pm_id].close();
24 God.watch._watchers[pm2_env.pm_id] = null;
25 delete God.watch._watchers[pm2_env.pm_id];
26 }
27
28 log('Initial watch ', pm2_env.watch)
29
30 var watch = pm2_env.watch
31
32 if(typeof watch == 'boolean' || util.isArray(watch) && watch.length === 0)
33 watch = pm2_env.pm_cwd;
34
35 log('Watching %s', watch);
36
37 var watch_options = {
38 ignored : pm2_env.ignore_watch || /[\/\\]\.|node_modules/,
39 persistent : true,
40 ignoreInitial : true,
41 cwd: pm2_env.pm_cwd
42 };
43
44 if (pm2_env.watch_options) {
45 watch_options = util._extend(watch_options, pm2_env.watch_options);
46 }
47
48 log('Watch opts', watch_options);
49
50 var watcher = chokidar.watch(watch, watch_options);
51
52 console.log('[Watch] Start watching', pm2_env.name);
53
54 watcher.on('all', function(event, path) {
55 var self = this;
56
57 if (self.restarting === true) {
58 log('Already restarting, skipping');
59 return false;
60 }
61
62 self.restarting = true;
63
64 console.log('Change detected on path %s for app %s - restarting', path, pm2_env.name);
65
66 setTimeout(function() {
67 God.restartProcessName(pm2_env.name, function(err, list) {
68 self.restarting = false;
69
70 if (err) {
71 log('Error while restarting', err);
72 return false;
73 }
74
75 return log('Process restarted');
76 });
77 }, (pm2_env.watch_delay || 0));
78
79 return false;
80 });
81
82 watcher.on('error', function(e) {
83 console.error(e.stack || e);
84 });
85
86 God.watch._watchers[pm2_env.pm_id] = watcher;
87
88 //return God.watch._watchers[pm2_env.name];
89 },
90 /**
91 * Description
92 * @method close
93 * @param {} id
94 * @return
95 */
96 God.watch.disableAll = function() {
97 var watchers = God.watch._watchers;
98
99 console.log('[Watch] PM2 is being killed. Watch is disabled to avoid conflicts');
100 for (var i in watchers) {
101 watchers[i].close && watchers[i].close();
102 watchers.splice(i, 1);
103 }
104 },
105
106 God.watch.disable = function(pm2_env) {
107 var watcher = God.watch._watchers[pm2_env.pm_id]
108 if (watcher) {
109 console.log('[Watch] Stop watching', pm2_env.name);
110 watcher.close();
111 delete God.watch._watchers[pm2_env.pm_id];
112 return true;
113 } else {
114 return false;
115 }
116 }
117};