Skip to content

Commit 2880a61

Browse files
authored
feat: [subprocess] support output as buffer (#447)
1 parent 5134d15 commit 2880a61

File tree

2 files changed

+21
-9
lines changed

2 files changed

+21
-9
lines changed

lib/subprocess.js

+9-9
Original file line numberDiff line numberDiff line change
@@ -126,13 +126,6 @@ class SubProcess extends EventEmitter {
126126
// actually spawn the subproc
127127
this.proc = spawn(this.cmd, this.args, this.opts);
128128

129-
if (this.proc.stdout) {
130-
this.proc.stdout.setEncoding(this.opts.encoding || 'utf8');
131-
}
132-
if (this.proc.stderr) {
133-
this.proc.stderr.setEncoding(this.opts.encoding || 'utf8');
134-
}
135-
136129
// this function handles output that we collect from the subproc
137130
/**
138131
*
@@ -184,13 +177,20 @@ class SubProcess extends EventEmitter {
184177
});
185178
};
186179

180+
const isBuffer = Boolean(this.opts.isBuffer);
181+
const encoding = this.opts.encoding || 'utf8';
182+
187183
if (this.proc.stdout) {
188-
this.proc.stdout.on('data', (chunk) => handleOutput({stdout: chunk.toString(), stderr: ''}));
184+
this.proc.stdout.on('data', (chunk) =>
185+
handleOutput({stdout: isBuffer ? chunk : chunk.toString(encoding), stderr: ''}),
186+
);
189187
handleStreamLines('stdout', this.proc.stdout);
190188
}
191189

192190
if (this.proc.stderr) {
193-
this.proc.stderr.on('data', (chunk) => handleOutput({stdout: '', stderr: chunk.toString()}));
191+
this.proc.stderr.on('data', (chunk) =>
192+
handleOutput({stdout: '', stderr: isBuffer ? chunk : chunk.toString(encoding)}),
193+
);
194194
handleStreamLines('stderr', this.proc.stderr);
195195
}
196196

test/subproc-specs.js

+12
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import B from 'bluebird';
22
import path from 'path';
33
import {exec, SubProcess} from '../lib';
44
import {getFixture} from './helpers';
5+
import _ from 'lodash';
56

67
// Windows doesn't understand SIGHUP
78
const stopSignal = process.platform === 'win32' ? 'SIGTERM' : 'SIGHUP';
@@ -189,6 +190,17 @@ describe('SubProcess', function () {
189190
await subproc.start();
190191
});
191192
});
193+
it('should get output as buffer', async function () {
194+
const stdout = await new B(async (resolve) => {
195+
subproc = new SubProcess(getFixture('echo'), ['foo'], {isBuffer: true});
196+
subproc.on('output', resolve);
197+
await subproc.start();
198+
});
199+
_.isString(stdout).should.be.false;
200+
_.isBuffer(stdout).should.be.true;
201+
202+
stdout.toString().trim().should.eql('foo');
203+
});
192204

193205
it('should get output by lines', async function () {
194206
subproc = new SubProcess('ls', [path.resolve(__dirname)]);

0 commit comments

Comments
 (0)