const logger = require('./logger.js'); const spawn = require('child_process').spawn; const sudo = require('sudo'); async function execute(command, args, useSudo, returnOnClose) { if (command === undefined || command.length === 0) { return; } if (returnOnClose === undefined) { returnOnClose = false; } let startTime = new Date().getTime(); let resultData = ""; let resultError = ""; command = command.trim(); let process; if (useSudo) { logger.debug('executing sudo command \'' + command + '\' (args: \'' + args + '\')...'); args.unshift(command); process = sudo(args, { cachePassword: true, prompt: 'sudo password:' }); } else { logger.debug('executing command \'' + command + '\' (args: \'' + args + '\')...'); process = spawn(command, args); } process.stdout.on('data', (data) => { resultData += data; }); process.stderr.on('data', (data) => { resultError += data; }); process.on('spawn', () => { logger.info('spawned command \'' + command + '\' (args: \'' + args + '\')'); if (!returnOnClose) { return; } }); process.on('error', (err) => { throw new Error(err); }); process.on('close', (code) => { let 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; logger.error(msg) return; } logger.debug(msg); if (returnOnClose) { return; } }); } module.exports = { execute }