UNPKG

@loaders.gl/worker-utils

Version:

Utilities for running tasks on worker threads

106 lines 3.12 kB
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty"; import * as ChildProcess from 'child_process'; import { getAvailablePort } from './process-utils'; const DEFAULT_PROPS = { command: '', arguments: [], port: 5000, autoPort: true, wait: 2000, onSuccess: processProxy => { console.log("Started ".concat(processProxy.props.command)); } }; export default class ChildProcessProxy { constructor() { let { id = 'browser-driver' } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _defineProperty(this, "id", void 0); _defineProperty(this, "props", { ...DEFAULT_PROPS }); _defineProperty(this, "childProcess", null); _defineProperty(this, "port", 0); _defineProperty(this, "successTimer", void 0); this.id = id; } async start(props) { props = { ...DEFAULT_PROPS, ...props }; this.props = props; const args = [...props.arguments]; this.port = Number(props.port); if (props.portArg) { if (props.autoPort) { this.port = await getAvailablePort(props.port); } args.push(props.portArg, String(this.port)); } return await new Promise((resolve, reject) => { try { this._setTimeout(() => { if (props.onSuccess) { props.onSuccess(this); } resolve({}); }); console.log("Spawning ".concat(props.command, " ").concat(props.arguments.join(' '))); const childProcess = ChildProcess.spawn(props.command, args, props.spawn); this.childProcess = childProcess; childProcess.stdout.on('data', data => { console.log(data.toString()); }); childProcess.stderr.on('data', data => { console.log("Child process wrote to stderr: \"".concat(data, "\".")); if (!props.ignoreStderr) { this._clearTimeout(); reject(new Error(data)); } }); childProcess.on('error', error => { console.log("Child process errored with ".concat(error)); this._clearTimeout(); reject(error); }); childProcess.on('close', code => { console.log("Child process exited with ".concat(code)); this.childProcess = null; this._clearTimeout(); resolve({}); }); } catch (error) { reject(error); } }); } async stop() { if (this.childProcess) { this.childProcess.kill(); this.childProcess = null; } } async exit() { let statusCode = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; try { await this.stop(); process.exit(statusCode); } catch (error) { console.error(error.message || error); process.exit(1); } } _setTimeout(callback) { if (Number(this.props.wait) > 0) { this.successTimer = setTimeout(callback, this.props.wait); } } _clearTimeout() { if (this.successTimer) { clearTimeout(this.successTimer); } } } //# sourceMappingURL=child-process-proxy.js.map