-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
84 lines (67 loc) · 1.83 KB
/
index.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
var write = require('fs').createWriteStream;
var fork = require('child_process').fork;
var through2 = require('through2');
var assign = require('object-assign');
var gutil = require('gulp-util');
var _spawnedProcess = null;
var spawnedProcesses = {};
var noop = function (chunk, enc, cb) {
return cb(null, chunk);
}
var _spawn = function(_conf) {
if (!_conf)
throw new gutil.PluginError('gulp-server-fork', 'No config provided');
if (typeof _conf == 'string')
_conf = { module: _conf };
if (!_conf.module)
throw new gutil.PluginError('gulp-server-fork', 'No module to fork provided');
var conf = assign({}, {
id: Date.now(),
timeout: 20 * 1000,
env: {},
logfile: null,
}, _conf)
return function(cb) {
var spawnedProcess = fork(conf.module, {
silent: true,
env: assign({}, process.env, conf.env)
});
if (conf.logfile && conf.logfile.length > 0) {
var logStream = write(conf.logfile);
spawnedProcess.stdout.pipe(logStream);
spawnedProcess.stderr.pipe(logStream);
}
var timerId = setTimeout(function() {
gutil.log(gutil.colors.magenta(conf.timeout + ' ms'), 'passed without recieving a ready event from the forked process.', gutil.colors.cyan('Continuing...'));
cb();
}, conf.timeout);
spawnedProcess.on('message', function(msg) {
if (msg == 'ready') {
clearTimeout(timerId);
return cb();
}
})
spawnedProcesses[conf.id] = spawnedProcess;
}
}
var _kill = function(id) {
return function(cb) {
if (id) {
if (spawnedProcesses[id])
spawnedProcesses[id].kill();
} else {
Object.keys(spawnedProcesses).forEach(function(id) {
spawnedProcesses[id].kill();
})
}
cb();
}
}
var spawn = function(conf) {
return through2.obj(noop, _spawn(conf));
}
var kill = function(id) {
return through2.obj(noop, _kill(id));
}
module.exports = spawn;
module.exports.kill = kill;