forked from remy/nodemon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nodemon.js
executable file
·291 lines (252 loc) · 8.61 KB
/
nodemon.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
#!/usr/bin/env node
var fs = require('fs'),
sys = require('sys'),
childProcess = require('child_process'),
path = require('path'),
spawn = childProcess.spawn,
meta = JSON.parse(fs.readFileSync(__dirname + '/package.json')),
exec = childProcess.exec,
flag = './.monitor',
nodeArgs = process.ARGV.splice(2), // removes 'node' and this script
app = nodeArgs[0],
node = null,
monitor = null,
ignoreFilePath = './.nodemonignore',
oldIgnoreFilePath = './nodemon-ignore',
ignoreFiles = [],
reIgnoreFiles = null,
timeout = 1000, // check every 1 second
restartDelay = 0, // controlled through arg --delay 10 (for 10 seconds)
restartTimer = null,
// create once, reuse as needed
reEscComments = /\\#/g,
reUnescapeComments = /\^\^/g, // note that '^^' is used in place of escaped comments
reComments = /#.*$/,
reTrim = /^(\s|\u00A0)+|(\s|\u00A0)+$/g,
reEscapeChars = /[.|\-[\]()\\]/g,
reAsterisk = /\*/g;
function startNode() {
sys.log('\x1B[32m[nodemon] starting node\x1B[0m');
var ext = path.extname(app);
if (ext === '.coffee') {
//coffeescript requires --nodejs --debug
var debugIndex = nodeArgs.indexOf('--debug');
if (debugIndex >= 0) {
nodeArgs.splice(debugIndex, 0, '--nodejs');
}
node = spawn('coffee', nodeArgs);
} else {
node = spawn('node', nodeArgs);
}
node.stdout.on('data', function (data) {
sys.print(data);
});
node.stderr.on('data', function (data) {
sys.error(data);
});
node.on('exit', function (code, signal) {
// exit the monitor, but do it gracefully
if (signal == 'SIGUSR2') {
// restart
startNode();
} else {
sys.log('\x1B[1;31m[nodemon] app crashed - waiting for file change before starting...\x1B[0m');
node = null;
}
});
}
function startMonitor() {
var cmd = 'find -L . -type f -newer ' + flag + ' -print';
exec(cmd, function (error, stdout, stderr) {
var files = stdout.split(/\n/);
files.pop(); // remove blank line ending and split
if (files.length) {
// filter ignored files
if (ignoreFiles.length) {
files = files.filter(function(file) {
return !reIgnoreFiles.test(file);
});
}
fs.writeFileSync(flag, '');
if (files.length) {
if (restartTimer !== null) clearTimeout(restartTimer);
restartTimer = setTimeout(function () {
sys.log('[nodemon] restarting due to changes...');
files.forEach(function (file) {
sys.log('[nodemon] ' + file);
});
sys.print('\n\n');
if (node !== null) {
node.kill('SIGUSR2');
} else {
startNode();
}
}, restartDelay);
}
}
setTimeout(startMonitor, timeout);
});
}
function addIgnoreRule(line, noEscape) {
// remove comments and trim lines
// this mess of replace methods is escaping "\#" to allow for emacs temp files
if (!noEscape) {
if (line = line.replace(reEscComments, '^^').replace(reComments, '').replace(reUnescapeComments, '#').replace(reTrim, '')) {
ignoreFiles.push(line.replace(reEscapeChars, '\\$&').replace(reAsterisk, '.*'));
}
} else if (line = line.replace(reTrim, '')) {
ignoreFiles.push(line);
}
reIgnoreFiles = new RegExp(ignoreFiles.join('|'));
}
function readIgnoreFile() {
fs.unwatchFile(ignoreFilePath);
// Check if ignore file still exists. Vim tends to delete it before replacing with changed file
path.exists(ignoreFilePath, function(exists) {
// if (!exists) {
// we'll touch the ignore file to make sure it gets created and
// if Vim is writing the file, it'll just overwrite it - but also
// prevent from constant file io if the file doesn't exist
// fs.writeFileSync(ignoreFilePath, "\n");
// setTimeout(readIgnoreFile, 500);
// return;
// }
sys.log('[nodemon] reading ignore list');
// ignoreFiles = ignoreFiles.concat([flag, ignoreFilePath]);
addIgnoreRule(flag);
addIgnoreRule(ignoreFilePath);
fs.readFileSync(ignoreFilePath).toString().split(/\n/).forEach(addIgnoreRule);
fs.watchFile(ignoreFilePath, { persistent: false }, readIgnoreFile);
});
}
function usage() {
sys.print([
'usage: nodemon [options] [script.js] [args]',
'e.g.: nodemon script.js localhost 8080',
'',
'Options:',
' --js monitor only JavaScript file changes',
' (default if ignore file not found)',
' -d n, --delay n throttle restart for "n" seconds',
' --debug enable node\'s native debug port',
' -v, --version current nodemon version',
' -h, --help this usage',
'',
'Note: if the script is omitted, nodemon will try "main" from package.json',
'',
'For more details see http://github.com/remy/nodemon/\n'
].join('\n'));
}
function controlArg(nodeArgs, label, fn) {
var i;
if ((i = nodeArgs.indexOf(label)) !== -1) {
fn(nodeArgs[i], i);
} else if ((i = nodeArgs.indexOf('-' + label.substr(0, 1))) !== -1) {
fn(nodeArgs[i], i);
} else if ((i = nodeArgs.indexOf('--' + label)) !== -1) {
fn(nodeArgs[i], i);
}
}
// attempt to shutdown the wrapped node instance and remove
// the monitor file as nodemon exists
function cleanup() {
node && node.kill();
fs.unlink(flag);
}
// control arguments test for "help" or "--help" or "-h", run the callback and exit
controlArg(nodeArgs, 'help', function () {
usage();
process.exit();
});
controlArg(nodeArgs, 'version', function () {
sys.print('v' + meta.version + '\n');
process.exit();
});
// look for delay flag
controlArg(nodeArgs, 'delay', function (arg, i) {
var delay = nodeArgs[i+1];
nodeArgs.splice(i, 2); // remove the delay from the arguments
app = nodeArgs[0];
if (delay) {
sys.log('[nodemon] Adding delay of ' + delay + ' seconds');
restartDelay = delay * 1000; // in seconds
}
});
controlArg(nodeArgs, 'js', function (arg, i) {
nodeArgs.splice(i, 1); // remove this flag from the arguments
// sys.log('[nodemon] monitoring all filetype changes');
addIgnoreRule('^((?!\.js$).)*$', true); // ignores everything except JS
app = nodeArgs[0];
});
controlArg(nodeArgs, '--debug', function (arg, i) {
nodeArgs.splice(i, 1);
app = nodeArgs[0];
nodeArgs.unshift('--debug'); // put it at the front
});
if (!nodeArgs.length || !path.existsSync(app)) {
// try to get the app from the package.json
// doing a try/catch because we can't use the path.exist callback pattern
// or we could, but the code would get messy, so this will do exactly
// what we're after - if the file doesn't exist, it'll throw.
try {
app = JSON.parse(fs.readFileSync('./package.json').toString()).main;
if (nodeArgs[0] == '--debug') {
nodeArgs.splice(1, 0, app);
} else {
nodeArgs.unshift(app);
}
} catch (e) {
// no app found to run - so give them a tip and get the feck out
usage();
process.exit();
}
}
sys.log('[nodemon] v' + meta.version);
// this was causing problems for a lot of people, so now not moving to the subdirectory
// process.chdir(path.dirname(app));
app = path.basename(app);
sys.log('\x1B[32m[nodemon] watching: ' + process.cwd() + '\x1B[0m');
sys.log('[nodemon] running ' + app);
startNode();
setTimeout(startMonitor, timeout);
path.exists(ignoreFilePath, function (exists) {
if (!exists) {
// try the old format
path.exists(oldIgnoreFilePath, function (exists) {
if (exists) {
sys.log('[nodemon] detected old style .nodemonignore');
ignoreFilePath = oldIgnoreFilePath;
} else {
// don't create the ignorefile, just ignore the flag & JS
addIgnoreRule(flag);
addIgnoreRule('^((?!\.js$).)*$', true);
}
});
} else {
readIgnoreFile();
}
});
// this little bit of hoop jumping is because sometimes the file can't be
// touched properly, and it send nodemon in to a loop of restarting.
// this way, the .monitor file is removed entirely, and recreated with
// permissions that anyone can remove it later (i.e. if you run as root
// by accident and then try again later).
if (path.existsSync(flag)) fs.unlinkSync(flag);
fs.writeFileSync(flag, '');
fs.chmodSync(flag, '666');
// remove the flag file on exit
process.on('exit', function (code) {
cleanup();
sys.log('[nodemon] exiting');
});
// usual suspect: ctrl+c exit
process.on('SIGINT', function () {
cleanup();
process.exit(0);
});
// on exception *inside* nodemon, shutdown wrapped node app
process.on('uncaughtException', function (err) {
sys.log('[nodemon] exception in nodemon killing node');
sys.error(err.stack);
cleanup();
});