highland-process
Version:
Utility that lets you turn a process into a highland stream.
72 lines (57 loc) • 1.55 kB
JavaScript
var _ = require('highland'),
errorsTo = require('highland-errors-to');
exports.from = function from(process) {
return _.merge([
_(process.stdout),
_(process.stderr).consume(errorConsumer())
]);
};
exports.through = function through(process) {
return function(stream) {
var errors,
errorsToResults,
out = exports.from(process);
errorsToResults = errorsTo(stream);
stream = errorsToResults.stream;
errors = errorsToResults.errors;
stream.pipe(process.stdin);
return _.merge([
out,
errors
]);
};
};
// TODO(ibash) remove this in favor of using the actual StreamError from highland
// ref: https://github.com/Datahero/datahero-node/issues/9676
function StreamError(err) {
this.__HighlandStreamError__ = true;
this.error = err;
}
function errorConsumer() {
var message = '';
return function consumer(error, value, push, next) {
var errorMessages;
if (error) {
push(error);
return next();
}
if (value !== _.nil) {
message += value;
}
if (message.indexOf('\n') !== -1) {
errorMessages = message.split('\n');
// don't create an error for the last message, since it might not be complete yet
for (var i = 0; i < errorMessages.length - 1; i++) {
push(new Error(errorMessages[i]));
}
message = errorMessages[errorMessages.length - 1];
}
if (value === _.nil) {
if (message) {
push(new Error(message));
}
return push(null, _.nil);
}
next();
};
}