2022-02-15 04:33:19 +01:00
|
|
|
const logger = require('./logger.js');
|
|
|
|
const spawn = require('child_process').spawn;
|
|
|
|
|
2022-03-03 03:35:34 +01:00
|
|
|
async function execute(command, args, returnOnClose) {
|
|
|
|
// return new Promise((resolve, reject) => {
|
|
|
|
if (command === undefined || command.length === 0) {
|
|
|
|
return;
|
|
|
|
// reject();
|
|
|
|
}
|
|
|
|
if (returnOnClose === undefined) {
|
|
|
|
returnOnClose = false;
|
2022-02-15 04:33:19 +01:00
|
|
|
}
|
|
|
|
var startTime = new Date().getTime();
|
|
|
|
var resultData = "";
|
|
|
|
var resultError = "";
|
|
|
|
command = command.trim();
|
|
|
|
logger.debug('executing command \'' + command + '\' (args: \'' + args + '\') ...');
|
|
|
|
try {
|
|
|
|
var process = spawn(command, args);
|
|
|
|
} catch (err) {
|
|
|
|
logger.error(err);
|
|
|
|
}
|
|
|
|
process.stdout.on('data', (data) => {
|
|
|
|
resultData += data;
|
|
|
|
});
|
|
|
|
process.stderr.on('data', (data) => {
|
|
|
|
resultError += data;
|
|
|
|
});
|
2022-03-03 03:35:34 +01:00
|
|
|
process.on('spawn', () => {
|
|
|
|
logger.info('spawned command \'' + command + '\' (args: \'' + args + '\')');
|
|
|
|
if (!returnOnClose) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
});
|
|
|
|
process.on('error', (err) => {
|
|
|
|
throw new Error(err);
|
|
|
|
// resultError += err;
|
|
|
|
});
|
2022-02-15 04:33:19 +01:00
|
|
|
process.on('close', (code) => {
|
|
|
|
var msg = 'command \'' + command + '\' (args: \'' + args + '\') finished with exit code ' + code + ' after ' + (new Date().getTime() - startTime) + 'ms';
|
|
|
|
if (resultData.length > 0) {
|
|
|
|
msg += " > data: " + resultData;
|
|
|
|
}
|
|
|
|
if (resultError.length > 0) {
|
|
|
|
msg += " >>> error: " + resultError;
|
2022-03-03 03:35:34 +01:00
|
|
|
throw new Error(msg);
|
|
|
|
// reject(msg);
|
2022-02-15 04:33:19 +01:00
|
|
|
}
|
2022-03-03 03:35:34 +01:00
|
|
|
if (returnOnClose) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
// resolve(msg);
|
2022-02-15 04:33:19 +01:00
|
|
|
});
|
2022-03-03 03:35:34 +01:00
|
|
|
|
|
|
|
// });
|
2022-02-15 04:33:19 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
execute
|
|
|
|
}
|