service-core/core/util.mjs

43 lines
1.2 KiB
JavaScript
Raw Normal View History

2020-09-07 00:47:53 +00:00
import path from 'path'
import { spawn } from 'child_process'
2020-09-07 18:15:11 +00:00
import { fileURLToPath, pathToFileURL } from 'url'
2020-09-07 00:47:53 +00:00
export function getPathFromRoot(add) {
const __dirname = path.dirname(fileURLToPath(import.meta.url));
return path.join(__dirname,'../', add)
}
2020-09-07 18:15:11 +00:00
export function getUrlFromRoot(add) {
return path.join(import.meta.url,'../../', add)
}
2020-09-07 01:25:03 +00:00
export function runCommand(command, options = [], folder = null, stream = function() {}) {
2020-09-07 00:47:53 +00:00
return new Promise(function(res, rej) {
2020-09-07 18:15:11 +00:00
stream(`[Command] ${folder ? folder : ''}${command} ${options.join(' ')}\n`)
2020-09-07 01:25:03 +00:00
let processor = spawn(command, options, {
shell: true,
cwd: folder,
})
let timeOuter = setTimeout(function() {
processor.stdin.write('n\n')
}, 250)
2020-09-07 00:47:53 +00:00
processor.stdout.on('data', function(data) {
stream(data.toString())
})
processor.stderr.on('data', function(data) {
stream(data.toString())
})
processor.on('error', function(err) {
2020-09-07 01:25:03 +00:00
clearInterval(timeOuter)
2020-09-07 00:47:53 +00:00
rej(err)
})
processor.on('exit', function (code) {
2020-09-07 01:25:03 +00:00
clearInterval(timeOuter)
2020-09-07 18:15:11 +00:00
if (code !== 0) {
return rej(new Error('Program returned error code: ' + code))
}
2020-09-07 00:47:53 +00:00
res(code)
})
})
}