remex/libs/commands.js
2022-03-15 01:36:47 +01:00

85 lines
2.4 KiB
JavaScript

const logger = require('./logger.js');
const { spawn } = require('child_process')
const cmds = new Map();
async function execute(endpoint) {
if (endpoint === undefined) {
return;
}
return new Promise((resolve, reject) => {
logger.info('executing command \'' + endpoint.command + '\' (args: \'' + endpoint.args + '\')...');
var cmd = spawn(endpoint.command, endpoint.args);
cmd.timestamp = new Date().getTime();
let result = '';
let error = '';
cmd.stdout.on('data', (data) => {
result += data;
});
cmd.stderr.on('data', (data) => {
error += data;
});
cmd.on('spawn', () => {
logger.info('spawned command \'' + endpoint.command + '\' (args: \'' + endpoint.args + '\')');
addCommand(cmd, endpoint);
if (endpoint.detach !== false) {
resolve();
}
});
cmd.on('error', (err) => {
error += err;
removeCommand(endpoint);
if (endpoint.detach !== false) {
reject();
}
});
cmd.on('close', (code) => {
removeCommand(endpoint);
let fn = logger.info;
let msg = 'command \'' + endpoint.command + '\' (args: \'' + endpoint.args + '\') finished with exit code ' + code + ' after ' + (new Date().getTime() - cmd.timestamp) + 'ms';
if (error !== undefined && error.length > 0) {
msg += ' >>> ' + error;
fn = logger.error;
reject(error);
}
if (result !== undefined && result.length > 0) {
msg += ' > ' + result;
}
fn(msg);
resolve(result);
});
});
}
function addCommand(command, endpoint) {
if (command === undefined || endpoint === undefined) {
return;
}
cmds.set(JSON.stringify(endpoint), command);
}
function removeCommand(endpoint) {
if (endpoint === undefined) {
return;
}
cmds.delete(JSON.stringify(endpoint));
}
function isCommandActive(endpoint) {
return endpoint !== undefined && cmds.has(JSON.stringify(endpoint));
}
function killCommand(endpoint) {
if (endpoint === undefined) {
return;
}
const command = cmds.get(JSON.stringify(endpoint));
if (command === undefined) {
return;
}
process.kill(command.pid);
}
module.exports = {
execute
}