UNPKG

1.58 kBJavaScriptView Raw
1'use strict';
2
3var cp = require('child_process');
4var fs = require('fs');
5var concat = require('concat-stream');
6var JSON = require('./json-buffer');
7
8var inputFile = process.argv[2];
9var ouptutFile = process.argv[3];
10
11var args = JSON.parse(fs.readFileSync(inputFile, 'utf8'));
12function output(result) {
13 fs.writeFileSync(ouptutFile, JSON.stringify(result));
14}
15
16var child = cp.spawn.apply(cp, args);
17var 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
23var complete = false;
24var stdout, stderr;
25child.stdout.pipe(concat(function (buf) {
26 stdout = buf.length ? buf : new Buffer(0);
27}));
28child.stderr.pipe(concat(function (buf) {
29 stderr = buf.length ? buf : new Buffer(0);
30}));
31child.on('error', function (err) {
32 output({pid: child.pid, error: err.message});
33});
34child.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
49if (options.timeout && typeof options.timeout === 'number') {
50 setTimeout(function () {
51 child.kill(options.killSignal || 'SIGTERM');
52 }, options.timeout);
53}
54if (options.input && (typeof options.input === 'string' || Buffer.isBuffer(options.input))) {
55 child.stdin.end(options.input);
56}