UNPKG

12.8 kBJavaScriptView Raw
1var debug = require('debug')('nodemon');
2const statSync = require('fs').statSync;
3var utils = require('../utils');
4var bus = utils.bus;
5var childProcess = require('child_process');
6var spawn = childProcess.spawn;
7var exec = childProcess.exec;
8var fork = childProcess.fork;
9var watch = require('./watch').watch;
10var config = require('../config');
11var child = null; // the actual child process we spawn
12var killedAfterChange = false;
13var noop = function () { };
14var restart = null;
15var psTree = require('pstree.remy');
16var path = require('path');
17var signals = require('./signals');
18
19function run(options) {
20 var cmd = config.command.raw;
21
22 var runCmd = !options.runOnChangeOnly || config.lastStarted !== 0;
23 if (runCmd) {
24 utils.log.status('starting `' + config.command.string + '`');
25 }
26
27 /*jshint validthis:true*/
28 restart = run.bind(this, options);
29 run.restart = restart;
30
31 config.lastStarted = Date.now();
32
33 var stdio = ['pipe', 'pipe', 'pipe'];
34
35 if (config.options.stdout) {
36 stdio = ['pipe', process.stdout, process.stderr];
37 }
38
39 if (config.options.stdin === false) {
40 stdio = [process.stdin, process.stdout, process.stderr];
41 }
42
43 var sh = 'sh';
44 var shFlag = '-c';
45
46 const binPath = process.cwd() + '/node_modules/.bin';
47
48 const spawnOptions = {
49 env: Object.assign({}, process.env, options.execOptions.env, {
50 PATH: binPath + ':' + process.env.PATH,
51 }),
52 stdio: stdio,
53 }
54
55 var executable = cmd.executable;
56
57 if (utils.isWindows) {
58 // if the exec includes a forward slash, reverse it for windows compat
59 // but *only* apply to the first command, and none of the arguments.
60 // ref #1251 and #1236
61 if (executable.indexOf('/') !== -1) {
62 executable = executable.split(' ').map((e, i) => {
63 if (i === 0) {
64 return path.normalize(e);
65 }
66 return e;
67 }).join(' ');
68 }
69 // taken from npm's cli: https://git.io/vNFD4
70 sh = process.env.comspec || 'cmd';
71 shFlag = '/d /s /c';
72 spawnOptions.windowsVerbatimArguments = true;
73 }
74
75 var args = runCmd ? utils.stringify(executable, cmd.args) : ':';
76 var spawnArgs = [sh, [shFlag, args], spawnOptions];
77
78 const firstArg = cmd.args[0] || '';
79
80 var inBinPath = false;
81 try {
82 inBinPath = statSync(`${binPath}/${executable}`).isFile();
83 } catch (e) {}
84
85 // hasStdio allows us to correctly handle stdin piping
86 // see: https://git.io/vNtX3
87 const hasStdio = utils.satisfies('>= 6.4.0 || < 5');
88
89 // forking helps with sub-process handling and tends to clean up better
90 // than spawning, but it should only be used under specific conditions
91 const shouldFork =
92 !config.options.spawn &&
93 !inBinPath &&
94 firstArg.indexOf('-') === -1 && // don't fork if there's a node exec arg
95 firstArg !== 'inspect' && // don't fork it's `inspect` debugger
96 executable === 'node' && // only fork if node
97 utils.version.major > 4 // only fork if node version > 4
98
99 if (shouldFork) {
100 var forkArgs = cmd.args.slice(1);
101 var env = utils.merge(options.execOptions.env, process.env);
102 stdio.push('ipc');
103 child = fork(options.execOptions.script, forkArgs, {
104 env: env,
105 stdio: stdio,
106 silent: !hasStdio,
107 });
108 utils.log.detail('forking');
109 debug('fork', sh, shFlag, args)
110 } else {
111 utils.log.detail('spawning');
112 child = spawn.apply(null, spawnArgs);
113 debug('spawn', sh, shFlag, args)
114 }
115
116 if (config.required) {
117 var emit = {
118 stdout: function (data) {
119 bus.emit('stdout', data);
120 },
121 stderr: function (data) {
122 bus.emit('stderr', data);
123 },
124 };
125
126 // now work out what to bind to...
127 if (config.options.stdout) {
128 child.on('stdout', emit.stdout).on('stderr', emit.stderr);
129 } else {
130 child.stdout.on('data', emit.stdout);
131 child.stderr.on('data', emit.stderr);
132
133 bus.stdout = child.stdout;
134 bus.stderr = child.stderr;
135 }
136 }
137
138 bus.emit('start');
139
140 utils.log.detail('child pid: ' + child.pid);
141
142 child.on('error', function (error) {
143 bus.emit('error', error);
144 if (error.code === 'ENOENT') {
145 utils.log.error('unable to run executable: "' + cmd.executable + '"');
146 process.exit(1);
147 } else {
148 utils.log.error('failed to start child process: ' + error.code);
149 throw error;
150 }
151 });
152
153 child.on('exit', function (code, signal) {
154 if (code === 127) {
155 utils.log.error('failed to start process, "' + cmd.executable +
156 '" exec not found');
157 bus.emit('error', code);
158 process.exit();
159 }
160
161 // If the command failed with code 2, it may or may not be a syntax error
162 // See: http://git.io/fNOAR
163 // We will only assume a parse error, if the child failed quickly
164 if (code === 2 && Date.now() < config.lastStarted + 500) {
165 utils.log.error('process failed, unhandled exit code (2)');
166 utils.log.error('');
167 utils.log.error('Either the command has a syntax error,');
168 utils.log.error('or it is exiting with reserved code 2.');
169 utils.log.error('');
170 utils.log.error('To keep nodemon running even after a code 2,');
171 utils.log.error('add this to the end of your command: || exit 1');
172 utils.log.error('');
173 utils.log.error('Read more here: https://git.io/fNOAG');
174 utils.log.error('');
175 utils.log.error('nodemon will stop now so that you can fix the command.');
176 utils.log.error('');
177 bus.emit('error', code);
178 process.exit();
179 }
180
181 // In case we killed the app ourselves, set the signal thusly
182 if (killedAfterChange) {
183 killedAfterChange = false;
184 signal = config.signal;
185 }
186 // this is nasty, but it gives it windows support
187 if (utils.isWindows && signal === 'SIGTERM') {
188 signal = config.signal;
189 }
190
191 if (signal === config.signal || code === 0) {
192 // this was a clean exit, so emit exit, rather than crash
193 debug('bus.emit(exit) via ' + config.signal);
194 bus.emit('exit');
195
196 // exit the monitor, but do it gracefully
197 if (signal === config.signal) {
198 return restart();
199 }
200
201 if (code === 0) { // clean exit - wait until file change to restart
202 if (runCmd) {
203 utils.log.status('clean exit - waiting for changes before restart');
204 }
205 child = null;
206 }
207 } else {
208 bus.emit('crash');
209 if (options.exitcrash) {
210 utils.log.fail('app crashed');
211 if (!config.required) {
212 process.exit(1);
213 }
214 } else {
215 utils.log.fail('app crashed - waiting for file changes before' +
216 ' starting...');
217 child = null;
218 }
219 }
220
221 if (config.options.restartable) {
222 // stdin needs to kick in again to be able to listen to the
223 // restart command
224 process.stdin.resume();
225 }
226 });
227
228 run.kill = function (noRestart, callback) {
229 // I hate code like this :( - Remy (author of said code)
230 if (typeof noRestart === 'function') {
231 callback = noRestart;
232 noRestart = false;
233 }
234
235 if (!callback) {
236 callback = noop;
237 }
238
239 if (child !== null) {
240 // if the stdin piping is on, we need to unpipe, but also close stdin on
241 // the child, otherwise linux can throw EPIPE or ECONNRESET errors.
242 if (options.stdin) {
243 process.stdin.unpipe(child.stdin);
244 }
245
246 if (utils.isWindows) {
247 // For the on('exit', ...) handler above the following looks like a
248 // crash, so we set the killedAfterChange flag
249 killedAfterChange = true;
250 }
251
252 /* Now kill the entire subtree of processes belonging to nodemon */
253 var oldPid = child.pid;
254 if (child) {
255 kill(child, config.signal, function () {
256 // this seems to fix the 0.11.x issue with the "rs" restart command,
257 // though I'm unsure why. it seems like more data is streamed in to
258 // stdin after we close.
259 if (child && options.stdin && child.stdin && oldPid === child.pid) {
260 child.stdin.end();
261 }
262 callback();
263 });
264 }
265 } else if (!noRestart) {
266 // if there's no child, then we need to manually start the process
267 // this is because as there was no child, the child.on('exit') event
268 // handler doesn't exist which would normally trigger the restart.
269 bus.once('start', callback);
270 restart();
271 } else {
272 callback();
273 }
274 };
275
276 // connect stdin to the child process (options.stdin is on by default)
277 if (options.stdin) {
278 process.stdin.resume();
279 // FIXME decide whether or not we need to decide the encoding
280 // process.stdin.setEncoding('utf8');
281
282 // swallow the stdin error if it happens
283 // ref: https://github.com/remy/nodemon/issues/1195
284 if (hasStdio) {
285 child.stdin.on('error', () => { });
286 process.stdin.pipe(child.stdin);
287 } else {
288 if (child.stdout) {
289 child.stdout.pipe(process.stdout);
290 } else {
291 utils.log.error('running an unsupported version of node ' +
292 process.version);
293 utils.log.error('nodemon may not work as expected - ' +
294 'please consider upgrading to LTS');
295 }
296 }
297
298 bus.once('exit', function () {
299 if (child && process.stdin.unpipe) { // node > 0.8
300 process.stdin.unpipe(child.stdin);
301 }
302 });
303 }
304
305 debug('start watch on: %s', config.options.watch);
306 if (config.options.watch !== false) {
307 watch();
308 }
309}
310
311function kill(child, signal, callback) {
312 if (!callback) {
313 callback = function () { };
314 }
315
316 if (utils.isWindows) {
317 // When using CoffeeScript under Windows, child's process is not node.exe
318 // Instead coffee.cmd is launched, which launches cmd.exe, which starts
319 // node.exe as a child process child.kill() would only kill cmd.exe, not
320 // node.exe
321 // Therefore we use the Windows taskkill utility to kill the process and all
322 // its children (/T for tree).
323 // Force kill (/F) the whole child tree (/T) by PID (/PID 123)
324 exec('taskkill /pid ' + child.pid + ' /T /F');
325 callback();
326 } else {
327 // we use psTree to kill the full subtree of nodemon, because when
328 // spawning processes like `coffee` under the `--debug` flag, it'll spawn
329 // it's own child, and that can't be killed by nodemon, so psTree gives us
330 // an array of PIDs that have spawned under nodemon, and we send each the
331 // configured signal (default: SIGUSR2) signal, which fixes #335
332 // note that psTree also works if `ps` is missing by looking in /proc
333 const sig = signal.replace('SIG', '');
334 psTree(child.pid, function (err, kids) {
335 if (psTree.hasPS) {
336 spawn('kill', ['-s', sig, child.pid].concat(kids.map(p => p.PID)))
337 .on('close', callback);
338 } else {
339 // make sure we kill from smallest to largest
340 const pids = kids.map(p => p.PID).concat(child.pid).sort();
341 pids.forEach(pid => {
342 exec('kill -' + signals[signal] + ' ' + pid, () => { });
343 });
344 callback();
345 }
346 });
347
348 }
349}
350
351// stubbed out for now, filled in during run
352run.kill = function (flag, callback) {
353 if (callback) {
354 callback();
355 }
356};
357run.restart = noop;
358
359bus.on('quit', function onQuit(code) {
360 if (code === undefined) {
361 code = 0;
362 }
363
364 // remove event listener
365 var exitTimer = null;
366 var exit = function () {
367 clearTimeout(exitTimer);
368 exit = noop; // null out in case of race condition
369 child = null;
370 if (!config.required) {
371 // Execute all other quit listeners.
372 bus.listeners('quit').forEach(function (listener) {
373 if (listener !== onQuit) {
374 listener();
375 }
376 });
377 process.exit(code);
378 } else {
379 bus.emit('exit');
380 }
381 };
382
383 // if we're not running already, don't bother with trying to kill
384 if (config.run === false) {
385 return exit();
386 }
387
388 // immediately try to stop any polling
389 config.run = false;
390
391 if (child) {
392 // give up waiting for the kids after 10 seconds
393 exitTimer = setTimeout(exit, 10 * 1000);
394 child.removeAllListeners('exit');
395 child.once('exit', exit);
396
397 kill(child, 'SIGINT');
398 } else {
399 exit();
400 }
401});
402
403bus.on('restart', function () {
404 // run.kill will send a SIGINT to the child process, which will cause it
405 // to terminate, which in turn uses the 'exit' event handler to restart
406 run.kill();
407});
408
409// remove the child file on exit
410process.on('exit', function () {
411 utils.log.detail('exiting');
412 if (child) { child.kill(); }
413});
414
415// because windows borks when listening for the SIG* events
416if (!utils.isWindows) {
417 bus.once('boot', () => {
418 // usual suspect: ctrl+c exit
419 process.once('SIGINT', () => bus.emit('quit', 130));
420 process.once('SIGTERM', () => {
421 bus.emit('quit', 143);
422 if (child) { child.kill('SIGTERM'); }
423 });
424 })
425}
426
427
428module.exports = run;