child_process#ChildProcess TypeScript Examples

The following examples show how to use child_process#ChildProcess. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts    From AIPerf with MIT License 7 votes vote down vote up
/**
 * run command as ChildProcess
 */
function getTunerProc(command: string, stdio: StdioOptions, newCwd: string, newEnv: any): ChildProcess {
    let cmd: string = command;
    let arg: string[] = [];
    let newShell: boolean = true;
    if(process.platform === "win32"){
        cmd = command.split(" ", 1)[0];
        arg = command.substr(cmd.length+1).split(" ");
        newShell = false;
    }
    const tunerProc: ChildProcess = spawn(cmd, arg, {
        stdio,
        cwd: newCwd,
        env: newEnv,
        shell: newShell
    });
    return tunerProc;
}
Example #2
Source File: utils.ts    From electron-playground with MIT License 7 votes vote down vote up
execute = async (): Promise<ChildProcess | null> => {
  await setupBinary()
  const child = spawn(getElectronBinaryPath(process.versions.electron), [path.join(SAVE_CODE_PATH, 'main.js'), '--inspect'])
  child.stdout.on('data', data => {
    console.log(`stdout: ${data}`)
  })

  child.stderr.on('data', data => {
    console.error(`stderr: ${data}`)
  })

  child.on('close', code => {
    console.log(`子进程退出,退出码 ${code}`)
  })
  return child
}
Example #3
Source File: ipcInterface.ts    From AIPerf with MIT License 6 votes vote down vote up
/**
     * Construct a IPC proxy
     * @param proc the process to wrap
     * @param acceptCommandTypes set of accepted commands for this process
     */
    constructor(proc: ChildProcess, acceptCommandTypes: Set<string>) {
        this.acceptCommandTypes = acceptCommandTypes;
        this.outgoingStream = <Writable>proc.stdio[ipcOutgoingFd];
        this.incomingStream = <Readable>proc.stdio[ipcIncomingFd];
        this.eventEmitter = new EventEmitter();
        this.readBuffer = Buffer.alloc(0);

        this.incomingStream.on('data', (data: Buffer) => { this.receive(data); });
        this.incomingStream.on('error', (error: Error) => { this.eventEmitter.emit('error', error); });
        this.outgoingStream.on('error', (error: Error) => { this.eventEmitter.emit('error', error); });
    }
Example #4
Source File: go-languageclient.ts    From atom-ide-golang with MIT License 6 votes vote down vote up
public startServerProcess(_projectPath: string): LanguageServerProcess | Promise<LanguageServerProcess> {
        const gopls = this.go.tool('gopls', ['-mode=stdio'], {
            env: process.env,
        }) as ChildProcess
        gopls.on('close', () => {
            if (!gopls.killed) {
                atom.notifications.addError(`${pkg.name} gopls the go language server exited unexpectedly or did not start`, {
                    dismissable: true,
                    description: 'Please make sure you have gopls installed `go get golang.org/x/tools/gopls`',
                    detail: this.processStdErr
                })
            }
        })
        return gopls as LanguageServerProcess
    }
Example #5
Source File: baseManager.ts    From Cromwell with MIT License 6 votes vote down vote up
startService = async ({ path, name, args, dir, sync, command, watchName, onVersionChange }: {
    path: string;
    name: string;
    args?: string[];
    dir?: string;
    sync?: boolean;
    command?: string;
    watchName?: keyof TServiceVersions;
    onVersionChange?: () => Promise<void>;
}): Promise<ChildProcess> => {
    if (! await fs.pathExists(path)) {
        logger.error('Base manager::startService: could not find startup script at: ', path);
        throw new Error();
    }

    const child = fork(path, args ?? [], {
        stdio: sync ? 'inherit' : 'pipe',
        cwd: dir ?? process.cwd(),
    });
    await saveProcessPid(name, process.pid, child.pid);
    serviceProcesses[name] = child;

    if (getStoreItem('environment')?.mode === 'dev' || command === 'build')
        child?.stdout?.on('data', buff => console.log(buff?.toString?.() ?? buff)); // eslint-disable-line

    child?.stderr?.on('data', buff => console.error(buff?.toString?.() ?? buff));

    if (watchName && onVersionChange) {
        startWatchService(watchName, onVersionChange);
    }
    return child;
}
Example #6
Source File: testing.ts    From openapi-cop with MIT License 6 votes vote down vote up
/**
 * Spawns a proxy server on a given port, using the default OpenAPI file.
 * Resources are created before execution and cleaned up thereafter.
 *
 * The `options` can be used to override the `child_process.spawn` options.
 */
export async function spawnProxyServer(
  proxyPort: number,
  targetPort: number,
  apiDocFile: string,
  options: any = {},
): Promise<ChildProcess> {
  // NOTE: for debugging use the options {detached: true, stdio: 'inherit'}
  const cp = spawn(
    'node',
    [
      '../../src/cli.js',
      '--port',
      proxyPort.toString(),
      '--target',
      `http://localhost:${targetPort}`,
      '--file',
      apiDocFile,
      '--verbose',
    ],
    { cwd: __dirname, stdio: 'pipe', detached: false, ...options },
  );

  await waitOn({ resources: [`tcp:localhost:${proxyPort}`] });

  return cp;
}
Example #7
Source File: utils.ts    From next-rpc with MIT License 6 votes vote down vote up
function redirectOutput(cp: ChildProcess) {
  if (VERBOSE) {
    process.stdin.pipe(cp.stdin);
    cp.stdout.pipe(process.stdout);
    cp.stderr.pipe(process.stderr);
  }
}
Example #8
Source File: gulpfile.ts    From SpaceEye with MIT License 6 votes vote down vote up
/**
 * Run Webpack with a config.
 *
 * @param config - Path to config to use
 * @param production - Whether the node environment should be production
 */
function runWebpack(config: string, production = false): ChildProcess {
    const options = production ? prodSpawnOptions : defaultSpawnOptions
    return spawn('webpack', ['--config', config], options)
}
Example #9
Source File: iDevices.ts    From iOSreExtension with Apache License 2.0 6 votes vote down vote up
public executeOnDeviceAsync(cmd: string): ChildProcess | undefined {
        // console.log("[W] executeOnDeviceAsync may cause executionLock errors!");
        if (this.selectedDevice === undefined) {
            vscode.window.showErrorMessage("No device selected");
            return;
        }
        // while (iDevices.executionLock) { }
        // iDevices.executionLock = true;
        let selection = this.selectedDevice as iDeviceDeps.iDeviceItem;
        iDeviceNodeProvider.nodeProvider.ensureiProxy(selection);
        let passpath = LKutils.shared.storagePath + "/" + LKutils.shared.makeid(10);
        writeFileSync(passpath, selection.iSSH_password);
        let terminalCommands: Array<string> = [];
        terminalCommands.push(" export SSHPASSWORD=$(cat \'" + passpath + "\')");
        // terminalCommands.push(" rm -f \'" + passpath + "\'");
        terminalCommands.push(" ssh-keygen -R \"[127.0.0.1]:" + selection.iSSH_mappedPort + "\" &> /dev/null");
        terminalCommands.push(" sshpass -p $SSHPASSWORD ssh -oStrictHostKeyChecking=no -p " + String(selection.iSSH_mappedPort) + " [email protected] \'" + cmd + "\'");
        let bashScript = "";
        let bashpath = LKutils.shared.storagePath + "/" + LKutils.shared.makeid(10);
        terminalCommands.forEach((cmd) => {
            bashScript += "\n";
            bashScript += cmd;
        });
        writeFileSync(bashpath, bashScript, 'utf8');
        let realCmd = "/bin/bash -C \'" + bashpath + "\'";
        let executeObject = exec(realCmd);
        // iDevices.executionLock = false;
        return executeObject;
    }
Example #10
Source File: process_tools.ts    From Daemon with GNU Affero General Public License v3.0 6 votes vote down vote up
export function killProcess(pid: string | number, process: ChildProcess, signal?: any) {
  try {
    if (os.platform() === "win32") {
      execSync(`taskkill /PID ${pid} /T /F`);
      console.log(`进程 ${pid} 已使用系统指令强制终止进程`);
      return true;
    }
    if (os.platform() === "linux") {
      execSync(`kill -s 9 ${pid}`);
      console.log(`进程 ${pid} 已使用系统指令强制终止进程`);
      return true;
    }
  } catch (err) {
    return signal ? process.kill(signal) : process.kill("SIGKILL");
  }
  return signal ? process.kill(signal) : process.kill("SIGKILL");
}
Example #11
Source File: execute-class-with-cp.ts    From node-java-connector with MIT License 6 votes vote down vote up
/**
 * Starts the class at the given path with given classpaths
 *
 * @export
 * @param {string} className Java classname to execute.
 * @param {string[]} [classPaths] optional Zip/Jar files to include to classpath.
 * @param {string[]} [args] optional arguments that will be appended while executing
 * @param {string} [jrePath] optional path to a JRE installation if other than default.
 * @returns {Promise<ChildProcess>}
 */
export async function executeClassWithCP(
  className: string,
  classPaths?: string[],
  args?: string[],
  jrePath?: string
): Promise<ChildProcess> {
  const jreInstallPath = resolveJREInstallPath(jrePath);
  const javaCommand = await getJavaCommand(jreInstallPath);
  const output = spawn(javaCommand, getClassArgs(className, classPaths, args));
  if (output.stderr) {
    output.stderr.pipe(process.stderr);
  }
  return output;
}
Example #12
Source File: index.ts    From Dimensions with MIT License 6 votes vote down vote up
/**
   * Spawns the compilation process
   * @param command - command to compile with
   * @param args - argument for the compilation
   */
  async _spawnCompileProcess(
    command: string,
    args: Array<string>
  ): Promise<ChildProcess | Agent.ContainerExecData> {
    return new Promise((resolve, reject) => {
      if (this.options.secureMode) {
        this.containerSpawn(`${command} ${args.join(' ')}`, containerBotFolder)
          .then(resolve)
          .catch(reject);
      } else {
        const p = spawn(command, [...args], {
          cwd: this.cwd,
        }).on('error', (err) => {
          reject(err);
        });
        resolve(p);
      }
    });
  }
Example #13
Source File: run.ts    From backstage with Apache License 2.0 6 votes vote down vote up
export async function waitForExit(
  child: ChildProcess & { exitCode: number | null },
  name?: string,
): Promise<void> {
  if (typeof child.exitCode === 'number') {
    if (child.exitCode) {
      throw new ExitCodeError(child.exitCode, name);
    }
    return;
  }

  await new Promise<void>((resolve, reject) => {
    child.once('error', error => reject(error));
    child.once('exit', code => {
      if (code) {
        reject(new ExitCodeError(code, name));
      } else {
        resolve();
      }
    });
  });
}
Example #14
Source File: lang-client.ts    From plugin-vscode with Apache License 2.0 6 votes vote down vote up
export async function init() {
    server = new StdioBallerinaLangServer(process.env.BALLERINA_HOME);
    server.start();

    client = await createStdioLangClient(server.lsProcess as ChildProcess, () => {/**/}, () => {/**/});
    if (!client) {
        // tslint:disable-next-line:no-console
        console.error("Could not initiate language client");
    }

    await client.init();
}
Example #15
Source File: process.spec.ts    From cli with Apache License 2.0 6 votes vote down vote up
jest.mock('child_process', () => ({
  spawn: jest
    .fn()
    .mockImplementationOnce(() => {
      const emitter = new EventEmitter();
      process.nextTick(() => emitter.emit('close', 0));
      return emitter as ChildProcess;
    })
    .mockImplementationOnce(() => {
      const emitter = new EventEmitter();
      process.nextTick(() => emitter.emit('close', 1));
      return emitter as ChildProcess;
    }),
}));
Example #16
Source File: polygon.ts    From node-launcher with Apache License 2.0 6 votes vote down vote up
async start(): Promise<ChildProcess[]> {

    const versions = Polygon.versions(this.client, this.network);
    const versionData = versions.find(({ version }) => version === this.version) || versions[0];
    if(!versionData)
      throw new Error(`Unknown version ${this.version}`);

    const {
      heimdallArgs,
      borArgs,
    } = await this.prestart(versionData);

    const heimdallInstance = this.startHeimdall(versionData, heimdallArgs);
    const borInstance = this.startBor(versionData, borArgs);

    this._instance = borInstance;
    this._instances = [
      borInstance,
      heimdallInstance,
    ];
    return this.instances();
  }
Example #17
Source File: abstract.runner.ts    From eslint-config-kit with MIT License 6 votes vote down vote up
public async run(
    command: string,
    collect = false,
    cwd: string = process.cwd()
  ): Promise<null | string> {
    const args: string[] = [command]

    const options: SpawnOptions = {
      cwd,
      stdio: collect ? 'pipe' : 'inherit',
      shell: true,
    }

    return new Promise<null | string>((resolve, reject) => {
      const child: ChildProcess = spawn(this.binary, args, options)

      if (collect) {
        child.stdout?.on('data', (data) =>
          resolve(data.toString().replace(/\r\n|\n/, ''))
        )
      }

      child.on('close', (code) => {
        if (code === 0) {
          resolve(null)
        } else {
          reject(
            new Error(
              MESSAGES.RUNNER_EXECUTION_ERROR(`${this.binary} ${command}`)
            )
          )
        }
      })
    })
  }
Example #18
Source File: index.d.ts    From nlw2-proffy with MIT License 6 votes vote down vote up
/**
Open stuff like URLs, files, executables. Cross-platform.

Uses the command `open` on OS X, `start` on Windows and `xdg-open` on other platforms.

@param target - The thing you want to open. Can be a URL, file, or executable. Opens in the default app for the file type. For example, URLs open in your default browser.
@returns The [spawned child process](https://nodejs.org/api/child_process.html#child_process_class_childprocess). You would normally not need to use this for anything, but it can be useful if you'd like to attach custom event listeners or perform other operations directly on the spawned process.

@example
```
import open = require('open');

// Opens the image in the default image viewer
(async () => {
	await open('unicorn.png', {wait: true});
	console.log('The image viewer app closed');

	// Opens the url in the default browser
	await open('https://sindresorhus.com');

	// Specify the app to open in
	await open('https://sindresorhus.com', {app: 'firefox'});

	// Specify app arguments
	await open('https://sindresorhus.com', {app: ['google chrome', '--incognito']});
})();
```
*/
declare function open(
	target: string,
	options?: open.Options
): Promise<ChildProcess>;
Example #19
Source File: gftp.ts    From yajsapi with GNU Lesser General Public License v3.0 6 votes vote down vote up
async _close() {
    if (!this._proc) return;
    const p: ChildProcess = this._proc;
    this._proc = null;

    // with contextlib.suppress(Exception):
    // await GftpDriver.shutdown();

    if (p.stdin) {
      p.stdin.destroy(); // p.stdin.close()
      // try {
      //   await Promise.any([waitProcess(p), sleep(10)]);
      //   return;
      // } catch (err) {}
    }
    p.kill();
    const ret_code = await p.signalCode;
    logger.debug(`GFTP server closed, code=${ret_code}`);
  }
Example #20
Source File: chain-events-nodes.spec.ts    From commonwealth with GNU General Public License v3.0 6 votes vote down vote up
// the following code ensures that child processes are terminated before the main process exits due to any reason
function childExit(children: ChildProcess[]) {
  process.stdin.resume();
  function exitHandler() {
    console.log('Ending child processes');
    for (let child of children) {
      if (child) {
        child.kill();
        child = null;
      }
    }
    console.log('All child processes closed');
  }
  // do something when app is closing
  process.on('exit', exitHandler);
  // catches ctrl+c event
  process.on('SIGINT', exitHandler);
  // catches "kill pid" (for example: nodemon restart)
  process.on('SIGUSR1', exitHandler);
  process.on('SIGUSR2', exitHandler);
  // catches uncaught exceptions
  process.on('uncaughtException', exitHandler);
}
Example #21
Source File: hackium-browser.ts    From hackium with ISC License 6 votes vote down vote up
constructor(
    connection: Connection,
    contextIds: string[],
    ignoreHTTPSErrors: boolean,
    defaultViewport?: Viewport,
    process?: ChildProcess,
    closeCallback?: BrowserCloseCallback,
  ) {
    super(connection, contextIds, ignoreHTTPSErrors, defaultViewport, process, closeCallback);
    this.connection = connection;
    this.__ignoreHTTPSErrors = ignoreHTTPSErrors;
    this.__defaultViewport = defaultViewport;
    this.__defaultContext = new HackiumBrowserContext(this.connection, this);
    this.__contexts = new Map();
    for (const contextId of contextIds) this.__contexts.set(contextId, new HackiumBrowserContext(this.connection, this, contextId));
    const listenerCount = this.connection.listenerCount('Target.targetCreated');

    if (listenerCount === 1) {
      this.connection.removeAllListeners('Target.targetCreated');
      this.connection.on('Target.targetCreated', this.__targetCreated.bind(this));
    } else {
      throw new Error('Need to reimplement how to intercept target creation. Submit a PR with a reproducible test case.');
    }
    this.log.debug('Hackium browser created');
  }
Example #22
Source File: apps.ts    From disco-cube-daemon with MIT License 6 votes vote down vote up
forkApp = (name: string, jsFilePath: string, args: string[]): RunningApp => {
  const logger = log4js.getLogger(name);
  logger.debug(`starting..`);

  let proc: ChildProcess | undefined = undefined;
  try {
    proc = fork(jsFilePath, args, {
      stdio: "pipe",
    });

    if (!proc) throw new Error(`fork failed, no proc`);
    if (!proc.stdout) throw new Error(`fork failed, no proc.stdout`);
    if (!proc.stderr) throw new Error(`fork failed, no proc.stderr`);

    proc.stdout.on("data", (data) => {
      logger.debug(`stdout: ${data}`);
    });

    proc.stderr.on("data", (data) => {
      logger.error(`stderr: ${data}`);
    });

    proc.on("close", (code) => {
      logger.debug(`child process exited with code ${code}`);
    });
  } catch (e) {
    logger.error(`spawn error`, e);
  }

  return {
    send: (data: any) => {
      proc?.send(data);
    },
    stop: () => {
      logger.debug(`stopping..`);
      if (proc) kill(proc.pid);
    },
  };
}
Example #23
Source File: index.ts    From nx-dotnet with MIT License 6 votes vote down vote up
export function runCommandUntil(
  command: string,
  criteria: (output: string) => boolean,
  { kill = true } = {},
): Promise<{ process: ChildProcess }> {
  const pm = getPackageManagerCommand();
  const p = exec(`${pm.runNx} ${command}`, {
    cwd: tmpProjPath(),
    env: { ...process.env, FORCE_COLOR: 'false' },
  });

  return new Promise((res, rej) => {
    let output = '';
    let complete = false;

    function checkCriteria(c: any) {
      output += c.toString();
      if (criteria(output)) {
        complete = true;
        res({ process: p });
        if (kill) {
          p.kill();
        }
      }
    }

    p.stdout?.on('data', checkCriteria);
    p.stderr?.on('data', checkCriteria);
    p.on('exit', (code) => {
      if (code !== 0 && !complete) {
        console.log(output);
      }
      rej(`Exited with ${code}`);
    });
  });
}
Example #24
Source File: rendering-process.ts    From open-design-sdk with Apache License 2.0 6 votes vote down vote up
_registerOutputListeners(process: ChildProcess): void {
    process.on('error', (err) => {
      this._console.error('Rendering: error>', err)
    })
    process.once('close', (code) => {
      this._process = null
      this._console.debug(`Rendering: closed with code: ${code}`)
    })

    process.stdout?.on('data', (data) => {
      this._console.debug('Rendering: stdout>', String(data).replace(/\n$/, ''))
    })
    process.stderr?.on('data', (data) => {
      this._console.error('Rendering: stderr>', String(data).replace(/\n$/, ''))
    })

    this._process = process
  }
Example #25
Source File: activateAndDeactivateCommand.ts    From tropicRPC with MIT License 6 votes vote down vote up
deactivateTropicCb: Function = () => {
  // dispose of saveListener
  if (saveListener) {
    saveListener.dispose();
  }

  // close opened server
  if (serverIsTurnedOn) {
    const killServerProcess: ChildProcess = spawn('kill', [`${serverProcess.pid}`]);
    setTimeout(() => {
      killServerProcess.kill('SIGINT');
      serverIsTurnedOn = false;
      vscode.window.showInformationMessage(`gRPC server has been shut off.`);
    }, 1000);
  }

  vscode.window.showInformationMessage(`tropicRPC is deactivated`);

  // hide and clear tropicRPC output channel
  tropicChannel.hide();
  tropicChannel.clear();

  // exit function
  return null;
}
Example #26
Source File: shell.ts    From command-bot with Apache License 2.0 6 votes vote down vote up
constructor(
    ctx: Context,
    private configuration: {
      itemsToRedact: string[]
      shouldTrackProgress?: boolean
      cwd?: string
      onChild?: (child: ChildProcess) => void
    },
  ) {
    this.logger = ctx.logger.child({ commandId: randomUUID() })
  }
Example #27
Source File: master.ts    From regax with MIT License 6 votes vote down vote up
async restartWorker(child: ChildProcess): Promise<void> {
    const pid = child.pid
    const workerInfo = this.workerInfos.get(pid)
    if (!workerInfo) return
    this.workerInfos.delete(pid)
    this.workers = this.workers.filter(w => w !== child)
    // this.rpc.rpcRegistry.unRegister(workerInfo.serverId)
    //  .catch((e: Error) => this.app.coreLogger.error('[regax-master] worker process unRegister error: ', e))
    await this.killWorker(pid)
    this.forkWorker(this.getWorkerOpts(workerInfo))
  }
Example #28
Source File: ipcInterface.ts    From AIPerf with MIT License 5 votes vote down vote up
/**
 * Create IPC proxy for tuner process
 * @param process_ the tuner process
 */
function createDispatcherInterface(process: ChildProcess): IpcInterface {
    return new IpcInterface(process, new Set([...CommandType.TUNER_COMMANDS, ...CommandType.ASSESSOR_COMMANDS]));
}
Example #29
Source File: remotePlaywright.ts    From Assistive-Webdriver with MIT License 5 votes vote down vote up
process(): ChildProcess {
    throw new Error("process() is not implemented.");
  }