51 lines
1.4 KiB
JavaScript
51 lines
1.4 KiB
JavaScript
"use strict";
|
|
|
|
// TODO: These should really be their own individual classes. Are
|
|
// there enough commonalities to warrant a base class?
|
|
|
|
const spawn = require('child_process').spawn;
|
|
const EventEmitter = require('events').EventEmitter;
|
|
|
|
module.exports.ChildProcessEmitter = class ChildProcessEmitter extends EventEmitter {
|
|
constructor(command, logger) {
|
|
super();
|
|
|
|
this.logger = logger;
|
|
|
|
var cmd = command[0],
|
|
args = command.slice(1);
|
|
|
|
this.childProcess = spawn(cmd, args);
|
|
|
|
this.childProcess.on('error', function(err) {
|
|
this.logger.error("process error", { class: this.constructor.name, name: name, err: String(err).trim() });
|
|
});
|
|
|
|
this.childProcess.on('close', function(code, signal) {
|
|
this.logger.debug("process closed", { class: this.constructor.name, name: name, code: code, signal: signal });
|
|
});
|
|
|
|
this.childProcess.stdout.on('data', (data) => {
|
|
var s = data.toString(), lines = s.split(/\n/g);
|
|
for (var i = 0, l = lines.length; i < l; i++) {
|
|
this.emit('message', lines[i]);
|
|
}
|
|
});
|
|
|
|
this.childProcess.stderr.on('data', (data) => {
|
|
this.logger.error('process stderr', { class: this.constructor.name, stderr: String(data).trim()});
|
|
});
|
|
}
|
|
|
|
kill() {
|
|
this.logger.debug("killing child process");
|
|
this.childProcess.kill();
|
|
}
|
|
|
|
send(message) {
|
|
this.childProcess.stdin.write(message);
|
|
}
|
|
}
|
|
|
|
// vim:set ts=2 sw=2 et:
|