Skip to content
This repository has been archived by the owner on Mar 14, 2022. It is now read-only.

Commit

Permalink
Pipe command output to stderr/stdout whilst keeping same interface (#419
Browse files Browse the repository at this point in the history
)
  • Loading branch information
JakeChampion authored Apr 3, 2017
1 parent dae6ee0 commit a5bcd54
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 51 deletions.
54 changes: 6 additions & 48 deletions lib/helpers/command-line.js
Original file line number Diff line number Diff line change
@@ -1,56 +1,14 @@
'use strict';

const childProcess = require('child_process');
const which = require('which');
const log = require('./log');
const windows = (process.platform.indexOf('win32') >= 0 || process.platform.indexOf('win64') >= 0);
const execa = require('execa');

function run(command, args, options) {
return new Promise(function(resolve, reject) {
let stdOut = '';
let stdErr = '';
function run(command, args) {
const result = execa(command, args);

if (windows) {
args.unshift('/c', command);
command = 'cmd';
}
result.stdout.pipe(process.stdout);
result.stderr.pipe(process.stderr);

try {
command = which.sync(command);
} catch (e) {
reject({ stdout: stdOut, stderr: stdErr, err: e });
}

const fullCommand = command + ' ' + args.join(' ');

const pro = childProcess.exec(fullCommand, options);

pro.on('error', function(error) {
log.secondaryError(error);
});

pro.on('close', function(code) {
const output = { 'stderr': stdErr, 'stdout': stdOut };

if (code !== 0) {
output.err = code;
reject(output);
}
resolve(output);
});

if (pro.stderr) {
pro.stderr.on('data', function(data) {
stdErr += data;
});
}

if (pro.stdout) {
pro.stdout.on('data', function(data) {
stdOut += data;
});
}
});
return result;
}

exports.run = run;
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"colors": "^1.1.2",
"configstore": "^2.1.0",
"denodeify": "^1.2.1",
"execa": "^0.6.3",
"falafel": "^1.2.0",
"findit": "^2.0.0",
"graphite": "0.0.6",
Expand Down
6 changes: 3 additions & 3 deletions test/helpers/command-line.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@ const commandLine = require('../../lib/helpers/command-line');
describe('Command line helper', function() {
it('should return output from stdout', function(done) {
commandLine.run('echo', ['test']).then(function(output) {
expect(output.stdout).to.be('test\n');
expect(output.stdout).to.be('test');
done();
});
});

it('should return output from stderr', function(done) {
commandLine.run('node', ['error']).then(function() {}, function(output) {
expect(output.stderr).to.contain('throw err;\n');
expect(output.err).to.be(1);
expect(output.stderr).to.contain('throw err;');
expect(output.code).to.be(1);
done();
});
});
Expand Down

0 comments on commit a5bcd54

Please sign in to comment.