1 | 'use strict';
|
2 |
|
3 | var cp = require('child_process');
|
4 | var fs = require('fs');
|
5 | var concat = require('concat-stream');
|
6 | var JSON = require('./json-buffer');
|
7 |
|
8 | var inputFile = process.argv[2];
|
9 | var ouptutFile = process.argv[3];
|
10 |
|
11 | var args = JSON.parse(fs.readFileSync(inputFile, 'utf8'));
|
12 | function output(result) {
|
13 | fs.writeFileSync(ouptutFile, JSON.stringify(result));
|
14 | }
|
15 |
|
16 | var child = cp.spawn.apply(cp, args);
|
17 | var options = (args[2] && typeof args[2] === 'object') ?
|
18 | args[2] :
|
19 | (args[1] && typeof args[1] === 'object' && !Array.isArray(args[1])) ?
|
20 | args[1] :
|
21 | {};
|
22 |
|
23 | var complete = false;
|
24 | var stdout, stderr;
|
25 | child.stdout.pipe(concat(function (buf) {
|
26 | stdout = buf.length ? buf : new Buffer(0);
|
27 | }));
|
28 | child.stderr.pipe(concat(function (buf) {
|
29 | stderr = buf.length ? buf : new Buffer(0);
|
30 | }));
|
31 | child.on('error', function (err) {
|
32 | output({pid: child.pid, error: err.message});
|
33 | });
|
34 | child.on('close', function (status, signal) {
|
35 | if (options.encoding && options.encoding !== 'buffer') {
|
36 | stdout = stdout.toString(options.encoding);
|
37 | stderr = stderr.toString(options.encoding);
|
38 | }
|
39 | output({
|
40 | pid: child.pid,
|
41 | output: [null, stdout, stderr],
|
42 | stdout: stdout,
|
43 | stderr: stderr,
|
44 | status: status,
|
45 | signal: signal
|
46 | });
|
47 | });
|
48 |
|
49 | if (options.timeout && typeof options.timeout === 'number') {
|
50 | setTimeout(function () {
|
51 | child.kill(options.killSignal || 'SIGTERM');
|
52 | }, options.timeout);
|
53 | }
|
54 | if (options.input && (typeof options.input === 'string' || Buffer.isBuffer(options.input))) {
|
55 | child.stdin.end(options.input);
|
56 | }
|