50 lines
1.4 KiB
JavaScript
50 lines
1.4 KiB
JavaScript
|
import { spawn } from 'child_process'
|
||
|
|
||
|
const argumentSplitter = new RegExp('("[^"]+")|([^ ]+)', 'g')
|
||
|
|
||
|
export function splitArguments(args) {
|
||
|
return Array.from(args.matchAll(argumentSplitter)).map(x => x[0])
|
||
|
}
|
||
|
|
||
|
function sendToStream(stream, source) {
|
||
|
return function(data) {
|
||
|
let cleaned = data.toString().replace(/\r\n/g, '\n').split('\n')
|
||
|
cleaned = cleaned.filter(x => Boolean(x.trim()))
|
||
|
for (let line of cleaned) {
|
||
|
stream(line, source)
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
export function runCommand(command, arg, stream = () => {}, returnProcess = false) {
|
||
|
let baseError = new Error('')
|
||
|
let options = splitArguments(arg)
|
||
|
|
||
|
if (!command) {
|
||
|
command = options[0]
|
||
|
options = options.slice(1)
|
||
|
}
|
||
|
|
||
|
return new Promise(function(res, rej) {
|
||
|
stream(`> ${command} ${options.join(' ')}\n`)
|
||
|
let processor = spawn(command, options, { shell: true })
|
||
|
|
||
|
processor.stdout.on('data', sendToStream(stream, 'stdout'))
|
||
|
processor.stderr.on('data', sendToStream(stream, 'stderr'))
|
||
|
processor.on('error', function(err) {
|
||
|
baseError.message = err.message
|
||
|
if (!returnProcess) rej(baseError)
|
||
|
})
|
||
|
processor.on('exit', function (code) {
|
||
|
if (code !== 0) {
|
||
|
baseError.message = 'Program returned error code: ' + code
|
||
|
if (!returnProcess) return rej(baseError)
|
||
|
}
|
||
|
if (!returnProcess) res(code)
|
||
|
})
|
||
|
if (returnProcess) {
|
||
|
res(processor)
|
||
|
}
|
||
|
})
|
||
|
}
|