const spawn = require('child_process').spawn; const EventEmitter = require('events').EventEmitter; const TAGREADER = 'tagreader'; const MP3PLAYER = 'mpg321'; const child_processes = new Map(); function launchChild(name, command) { var cmd = command[0], args = command.slice(1); return spawn(cmd, args); } function setupEmitter(name, emitter, child) { exports[name] = emitter; child.on('error', function(err) { emitter.emit('process_error', err); }); child.on('close', function(code, signal) { emitter.emit('close', code, signal); }); child.stdout.on('data', (data) => { var s = data.toString(), lines = s.split(/\n/g); for (var i = 0, l = lines.length; i < l; i++) { emitter.emit('message', lines[i]); } }); child.stderr.on('data', (data) => { emitter.emit('error', data); }); return emitter; } exports.init = function(config) { // Set up tag reader var tagreader = launchChild(TAGREADER, config.tag_reader); var tagreader_emitter = new EventEmitter(); setupEmitter(TAGREADER, tagreader_emitter, tagreader); child_processes.set(TAGREADER, tagreader); exports.tagreader = tagreader_emitter; // set up mp3 player var mp3player = launchChild(MP3PLAYER, config.mpg321); var mp3player_emitter = new EventEmitter(); setupEmitter(MP3PLAYER, mp3player_emitter, mp3player); child_processes.set(MP3PLAYER, mp3player); exports.mp3player = mp3player_emitter; }; exports.exitHandler = function(options, err) { console.log('[player] closing children'); if (err) console.log(err.stack); child_processes.forEach((p) => { p.kill(); }); if (options.exit) { process.exit(); } }; // vim:set ts=2 sw=2 et: