This repository has been archived by the owner on Jan 19, 2020. It is now read-only.
forked from wilk/node-certification
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
73 lines (51 loc) · 1.89 KB
/
utils.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
// Using: http://stackoverflow.com/questions/22646996/how-do-i-run-a-node-js-script-from-within-another-node-js-script
'use strict';
var childProcess = require('child_process');
var opener = require('opener');
module.exports = {
runScript : function (scriptPath, pointers, callback) {
var self = this;
// Clean previous executions (like express);
for (var i in pointers) {
pointers[i].shutdown();
}
pointers = [];
// keep track of whether callback has been invoked to prevent multiple invocations
var invoked = false;
var process = childProcess.fork(scriptPath);
pointers.push(process);
// Function to propagate errors
process.callbackError = function (code) {
if (invoked) { return }
invoked = true;
var err = code === 0 ? null : new Error('exit code ' + code);
self.callback(err);
};
// Own kill function, remove listener and kill itself
process.shutdown = function () {
// Get rid of the exit listener since this is a planned exit.
this.removeListener("exit", this.callbackError);
this.kill("SIGTERM");
};
// execute the callback once the process has finished running
process.on('exit', process.callbackError);
// listen for errors as they may prevent the exit event from firing
process.on('error',function (err) {
if (invoked) { return }
invoked = true;
callback(err);
});
return pointers;
},
callback: function (err) {
if (err) {
console.log('Error running script');
console.log(err);
}
console.log('Pres any key to go back to menu');
},
opener: function (url) {
url = url || 'http://localhost:12345';
opener(url);
}
};