service-core/core/util.mjs

49 lines
1.4 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
2020-09-08 08:11:42 +00:00
export default class Util {
constructor(root_import_meta_url) {
this._root_import_meta_url = root_import_meta_url
}
2020-09-07 00:47:53 +00:00
2020-09-08 08:11:42 +00:00
getPathFromRoot(add) {
const __dirname = path.dirname(fileURLToPath(this._root_import_meta_url));
return path.join(__dirname,'./', add)
}
2020-09-07 18:15:11 +00:00
2020-09-08 08:11:42 +00:00
getUrlFromRoot(add) {
return path.join(this._root_import_meta_url,'../', add)
}
runCommand(command, options = [], folder = null, stream = function() {}) {
return new Promise(function(res, rej) {
stream(`[Command] ${folder ? folder : ''}${command} ${options.join(' ')}\n`)
let processor = spawn(command, options, {
shell: true,
cwd: folder,
})
let timeOuter = setTimeout(function() {
processor.stdin.write('n\n')
}, 250)
processor.stdout.on('data', function(data) {
stream(data.toString())
})
processor.stderr.on('data', function(data) {
stream(data.toString())
})
processor.on('error', function(err) {
clearInterval(timeOuter)
rej(err)
})
processor.on('exit', function (code) {
clearInterval(timeOuter)
if (code !== 0) {
return rej(new Error('Program returned error code: ' + code))
}
res(code)
})
2020-09-07 00:47:53 +00:00
})
2020-09-08 08:11:42 +00:00
}
2020-09-07 00:47:53 +00:00
}