Skip to content

Instantly share code, notes, and snippets.

@stoefln
Created December 5, 2022 17:48
Show Gist options
  • Save stoefln/173cd60798e433494422e6adf539fb71 to your computer and use it in GitHub Desktop.
Save stoefln/173cd60798e433494422e6adf539fb71 to your computer and use it in GitHub Desktop.
static async execCommandMain(
command,
input,
quitOnStringFound,
consoleLog = line => {
console.debug(line)
},
directory,
replaceStrings
) {
let promise = new Promise((resolve, reject) => {
if (replaceStrings) {
command = replaceAllDict(command, replaceStrings)
}
let args = parseArgsStringToArgv(command)
command = args.shift()
if (!consoleLog) {
consoleLog = line => {}
}
consoleLog('Spawn: ' + command + ' Args: ' + (args && JSON.stringify(args)))
const options = {}
if (directory) {
directory = directory.trim()
if (replaceStrings) {
directory = replaceAllDict(directory, replaceStrings)
}
options.cwd = directory
}
var child = spawn(command, args, options)
child.stdout.setEncoding('utf8')
var result = ''
child.stdout.on('data', chunk => {
result += chunk
handleQuitOnStringFound()
})
child.stderr.on('data', chunk => {
result += chunk
consoleLog('error chunk: ' + chunk)
handleQuitOnStringFound()
})
child.on('close', code => {
const message = ` (quit with code ${code})`
if (code !== 0) {
result += message
}
if (code === 0 || code === null) {
resolve(result)
} else {
const directoryString = directory ? ' in directory ' + directory : ''
result += `\nError occued while executing command "${command}"${directoryString}. Command arguments: [${args}]`
reject(new Error(result))
}
})
child.on('error', function(err) {
reject(err)
})
if (input) {
consoleLog('send input: ' + input)
//child.stdin.setEncoding('utf8')
child.stdin.write(input)
child.stdin.end()
}
let handleQuitOnStringFound = () => {
if (quitOnStringFound) {
if (result.indexOf(quitOnStringFound) != -1) {
if (consoleLog) {
console.debug('quitOnStringFound')
}
child.kill('SIGINT')
}
}
}
})
return promise
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment