pi-rfid-jukebox/jukebox/child-process.js

51 lines
1.4 KiB
JavaScript
Raw Normal View History

"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 {
2017-04-09 17:55:11 +00:00
constructor(command, logger) {
super();
2017-04-09 17:55:11 +00:00
this.logger = logger;
var cmd = command[0],
args = command.slice(1);
this.childProcess = spawn(cmd, args);
this.childProcess.on('error', function(err) {
2017-04-09 18:08:22 +00:00
this.logger.error("process error", { class: this.constructor.name, name: name, err: String(err).trim() });
});
this.childProcess.on('close', function(code, signal) {
2017-04-09 18:08:22 +00:00
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) => {
2017-04-09 18:08:22 +00:00
this.logger.error('process stderr', { class: this.constructor.name, stderr: String(data).trim()});
});
}
kill() {
2017-04-09 17:55:11 +00:00
this.logger.debug("killing child process");
this.childProcess.kill();
}
send(message) {
this.childProcess.stdin.write(message);
}
}
// vim:set ts=2 sw=2 et: