ninwa/libs/cli.js

44 lines
1.4 KiB
JavaScript
Raw Normal View History

2022-02-15 04:33:19 +01:00
const logger = require('./logger.js');
const spawn = require('child_process').spawn;
function execute(command, args) {
return new Promise((resolve, reject) => {
if (command == undefined || command.length == 0) {
reject();
}
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;
});
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;
reject(msg);
}
resolve(msg);
});
process.on('error', (err) => {
resultError += err;
});
});
}
module.exports = {
execute
}