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

59 lines
1.6 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;
2017-04-09 19:08:32 +00:00
this.stderrFilters = [];
2017-04-09 17:55:11 +00:00
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) => {
2017-04-09 19:08:32 +00:00
var lines = data.toString().split(/\n/g);
lines.map(line => line.trim())
.filter(line => line.length)
.map(line => this.emit('message', line));
});
this.childProcess.stderr.on('data', (data) => {
2017-04-09 19:08:32 +00:00
var line = data.toString().trim();
var filtered = this.stderrFilters.reduce((filter, filtered) => {
return filtered || filter(line);
}, false);
if (filtered) {
return;
}
this.logger.error('process stderr', { class: this.constructor.name, stderr: line});
});
}
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: