-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathrun-module-as-observable-fork.js
67 lines (67 loc) · 2.51 KB
/
run-module-as-observable-fork.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
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const child_process_1 = require("child_process");
const path_1 = require("path");
const rxjs_1 = require("rxjs");
const treeKill = require('tree-kill');
function runModuleAsObservableFork(cwd, modulePath, exportName,
// tslint:disable-next-line:no-any
args) {
return new rxjs_1.Observable(obs => {
const workerPath = path_1.resolve(__dirname, './run-module-worker.js');
const debugArgRegex = /--inspect(?:-brk|-port)?|--debug(?:-brk|-port)/;
const execArgv = process.execArgv.filter((arg) => {
// Remove debug args.
// Workaround for https://github.com/nodejs/node/issues/9435
return !debugArgRegex.test(arg);
});
const forkOptions = {
cwd,
execArgv,
};
// TODO: support passing in a logger to use as stdio streams
// if (logger) {
// (forkOptions as any).stdio = [
// 'ignore',
// logger.info, // make it a stream
// logger.error, // make it a stream
// ];
// }
const forkedProcess = child_process_1.fork(workerPath, undefined, forkOptions);
// Cleanup.
const killForkedProcess = () => {
if (forkedProcess && forkedProcess.pid) {
treeKill(forkedProcess.pid, 'SIGTERM');
}
};
// Handle child process exit.
const handleChildProcessExit = (code) => {
killForkedProcess();
if (code && code !== 0) {
obs.error();
}
obs.next({ success: true });
obs.complete();
};
forkedProcess.once('exit', handleChildProcessExit);
forkedProcess.once('SIGINT', handleChildProcessExit);
forkedProcess.once('uncaughtException', handleChildProcessExit);
// Handle parent process exit.
const handleParentProcessExit = () => {
killForkedProcess();
};
process.once('exit', handleParentProcessExit);
process.once('SIGINT', handleParentProcessExit);
process.once('uncaughtException', handleParentProcessExit);
// Run module.
forkedProcess.send({
hash: '5d4b9a5c0a4e0f9977598437b0e85bcc',
modulePath,
exportName,
args,
});
// Teardown logic. When unsubscribing, kill the forked process.
return killForkedProcess;
});
}
exports.runModuleAsObservableFork = runModuleAsObservableFork;