child_process#spawn TypeScript Examples

The following examples show how to use child_process#spawn. 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 malagu with MIT License 8 votes vote down vote up
export function spawnProcess(command: string, args: string[], options: any) {
    return new Promise<any>((resolve, reject) => {
        if (options && options.stdio === 'inherit') {
            spawnSync(command, args, options);
            resolve({});
        } else {
            const child = spawn(command, args, options);
            let stdout = '';
            let stderr = '';
            child.stdout.setEncoding('utf8');
            child.stderr.setEncoding('utf8');
            child.stdout.on('data', (data: any) => {
                stdout += data;
            });
            child.stderr.on('data', (data: any) => {
                stderr += data;
            });
            child.on('error', (err: any) => {
                reject(err);
            });
            child.on('close', (exitCode: number) => {
                if (exitCode !== 0) {
                    reject(new SpawnError(`${command} ${args.join(' ')} failed with code ${exitCode}`, stdout, stderr));
                } else {
                    resolve({ stdout, stderr });
                }
            });
        }
    });
}
Example #2
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 #3
Source File: utils.ts    From airnode with MIT License 7 votes vote down vote up
killBackgroundProcess = (processToKill: ChildProcessWithoutNullStreams) => {
  // We need to gracefully kill the Airnode docker otherwise it remains running on background
  //
  // The following reliably kills the Airnode process for unix, but it throws for windows.
  // See: https://azimi.me/2014/12/31/kill-child_process-node-js.html
  try {
    process.kill(-processToKill.pid!);
  } catch (e) {
    // See: https://stackoverflow.com/a/28163919
    spawn('taskkill', ['/pid', processToKill.pid!.toString(), '/f', '/t']);
  }
}
Example #4
Source File: utils.ts    From heroku-docker-deploy with MIT License 7 votes vote down vote up
runCommand = async (command: string, { options, env }: RunCommandOptions = {}): Promise<number> => {
  const parts = command.split(' ').filter((part) => Boolean(part));
  if (parts.length === 0) throw new Error('Wrong command provided');

  return new Promise<number>((resolve, reject) => {
    const args = parts.slice(1, parts.length);

    const processEnv = Object.create(process.env);
    const commandEnv = Object.assign(processEnv, env);

    const command = spawn(parts[0], args, {
      ...options,
      env: commandEnv,
      stdio: 'inherit',
    });

    const onExit = (code: number) => {
      if (code === 0) resolve(code);
      else reject(code);
    };

    command.on('exit', onExit);
    command.on('close', onExit);
    command.on('error', reject);
  });
}
Example #5
Source File: util.ts    From riju with MIT License 7 votes vote down vote up
export async function run(
  args: string[],
  log: (msg: string) => void,
  options?: Options
) {
  options = options || {};
  const input = options.input;
  const check = options.check === undefined ? true : options.check;
  delete options.input;
  delete options.check;
  const proc = spawn(args[0], args.slice(1), options);
  if (typeof input === "string") {
    proc.stdin!.end(input);
  }
  let output = "";
  proc.stdout!.on("data", (data: Buffer) => {
    output += `${data}`;
  });
  proc.stderr!.on("data", (data: Buffer) => {
    output += `${data}`;
  });
  return await new Promise((resolve, reject) => {
    proc.on("error", reject);
    proc.on("close", (code: number, signal: string) => {
      output = output.trim();
      if (output) {
        log(`Output from ${args[0]}:\n` + output);
      }
      if (code === 0 || !check) {
        resolve(code);
      } else {
        reject(`command ${args[0]} failed with error code ${signal || code}`);
      }
    });
  });
}
Example #6
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 #7
Source File: spawn-process.ts    From nx-plugins with MIT License 6 votes vote down vote up
export function spawnProcess(
  command: string,
  args: string[] = [],
  { silent, env = process.env, ...options }: ProcessOptions = {},
): Observable<ProcessOutput> {
  return new Observable<ProcessOutput>((observer) => {
    const child = spawn(command, args, { ...options, env: processEnv(env) });

    if (!silent) {
      console.log(`${command} ${args.join(' ')}`);
    }

    const processExitListener = () => {
      observer.complete();
      child.kill();
    };
    process.on('exit', processExitListener);
    if (!('stdio' in options)) {
      child.stdout.on('data', (data) => {
        observer.next({ type: 'OUT', data });
      });
      child.stderr.on('data', (data) => {
        observer.next({ type: 'ERR', data });
      });
    }
    child.on('close', (code) => {
      if (code === 0) {
        observer.complete();
      } else {
        observer.error();
      }

      process.removeListener('exit', processExitListener);
    });
  });
}
Example #8
Source File: index.ts    From bluebubbles-server with Apache License 2.0 6 votes vote down vote up
/**
     * Runs caffeinate until the current process is killed
     */
    start() {
        if (this.isCaffeinated) return;
        const myPid = process.pid;

        // Spawn the child process
        // -i: Create an assertion to prevent the system from idle sleeping.
        // -m: Create an assertion to prevent the disk from idle sleeping.
        // -s: Create an assertion to prevent the system from sleeping
        // -w: Waits for the process with the specified pid to exit.
        this.childProc = spawn("caffeinate", ["-i", "-m", "-s", "-w", myPid.toString()], { detached: true });
        Server().log(`Spawned Caffeinate with PID: ${this.childProc.pid}`);
        this.isCaffeinated = true;

        // Setup listeners
        this.childProc.on("close", this.onClose);
        this.childProc.on("exit", this.onClose);
        this.childProc.on("disconnect", this.onClose);
        this.childProc.on("error", this.onClose);
    }
Example #9
Source File: shell.ts    From Cromwell with MIT License 6 votes vote down vote up
runShellCommand = (command: string, cwd?: string): Promise<void> => {
    logger.info('Running shell command: ' + command);

    return new Promise<void>(done => {
        const proc = spawn(command, [],
            { shell: true, stdio: 'pipe', cwd: cwd ?? process.cwd() });

        if (proc.stderr && proc.stderr.on) {
            proc.stderr.on('data', (data) => {
                logger.warn(data.toString ? data.toString() : data);
            });
        }
        if (proc.stdout && proc.stdout.on) {
            proc.stdout.on('data', (data) => {
                logger.log(data.toString ? data.toString() : data);
            });
        }

        proc.on('close', () => {
            done();
        });
    });
}
Example #10
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 #11
Source File: index.ts    From angular-electron-admin with Apache License 2.0 6 votes vote down vote up
function startElectron(): void {
  const args = [
    '--inspect=5858',
    path.join(__dirname, '../../dist/main/main.js')
  ];

  if (process.env.npm_execpath.endsWith('yarn.js')) {
    args.push(...process.argv.slice(3));
  }
  if (process.env.npm_execpath.endsWith('npm-cli.js')) {
    args.push(...process.argv.slice(2));
  }


  electronProcess = spawn(require('electron') as unknown as string, args);

  electronProcess.stdout.on('data', data => electronLog(data, 'blue'));
  electronProcess.stderr.on('data', data => electronLog(data, 'red'));

  electronProcess.on('close', () => {
    if (!manualRestart) {
      process.exit();
    }
  });
}
Example #12
Source File: buildDocker.ts    From h1z1-server with GNU General Public License v3.0 6 votes vote down vote up
function buildAllImages(imageTag:string) {
  images.forEach((image) => {
    const { name, version, fileName } = image;
    const buildProcess = spawn("docker", [
      "build",
      "-t",
      `h1emu/${name}:${imageTag}`,
      "-f",
      `./docker/${version}/${fileName}.Dockerfile`,
      "./",
    ]);

    buildProcess.stdout.on("data", (data) => {
      console.log(`${name}(${version}): ${data}`);
    });

    buildProcess.stderr.on("data", (data) => {
      console.log(`${name}(${version}): ${data}`);
    });

    buildProcess.on("close", (code) => {
      if (code) {
        throw new Error(`${name}(${version}) exited with code ${code}`);
      } else {
        console.log(`${name}(${version}) builded!`);
      }
    });
  });
}
Example #13
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 #14
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 #15
Source File: run-alpha.ts    From ow-mod-manager with MIT License 6 votes vote down vote up
export async function runAlpha(
  { closeOnPlay, logToSocket, alphaPath, owamlPath }: Settings,
  port: number
) {
  const owamlParams = [];
  if (!closeOnPlay && logToSocket) {
    owamlParams.push(`-consolePort ${port}`);
  }
  if (alphaPath) {
    owamlParams.push(`-gamePath "${alphaPath}"`);
  }

  spawn(EXE_FILE, owamlParams, {
    shell: true,
    cwd: owamlPath,
    detached: true,
  });

  if (closeOnPlay) {
    waitAndQuit();
  }
}
Example #16
Source File: execDaemon.ts    From Serverless-Devs with MIT License 6 votes vote down vote up
export function execDaemon(filename: string, config?: IConfig) {
  const filePath = path.join(__dirname, 'daemon', filename);
  if (!fs.existsSync(filePath)) return;
  const subprocess = spawn(process.execPath, [filePath], {
    detached: true,
    stdio: 'ignore',
    env: { ...process.env, ...config },
  });
  subprocess.unref();
}
Example #17
Source File: System.ts    From Dimensions with MIT License 6 votes vote down vote up
dockerCopy = (
  fileOrDirectoryPath: string,
  containerID: string,
  targetPath: string
): Promise<void> => {
  return new Promise((resolve, reject) => {
    const p = spawn('docker', [
      'cp',
      fileOrDirectoryPath,
      `${containerID}:${targetPath}`,
    ]);
    p.on('error', (err) => {
      reject(err);
    });
    p.on('close', (code) => {
      if (code === 0) {
        resolve();
      } else {
        reject(
          `dockerCopy from ${fileOrDirectoryPath} to ${containerID}:${targetPath} exited with code ${code}`
        );
      }
    });
  });
}
Example #18
Source File: 6_ssr.spec.ts    From elephize with MIT License 6 votes vote down vote up
getFromProcess = (command: string, args: string[]): Promise<string> => {
  return new Promise<string>((resolve, reject) => {
    const child = spawn(command, args);
    let cont = '';
    child.stdout.on('data', (data) => cont += data);
    child.on('close', (code) => {
      if (code && code > 0) {
        reject(new Error(''));
      } else {
        resolve(cont);
      }
    });
  });
}
Example #19
Source File: dev-server.ts    From image-optimizer with MIT License 6 votes vote down vote up
function startElectron () {
  if (electronProcess) return

  const args = ['.', rendererPort] as SpawnOptionsWithoutStdio

  electronProcess = spawn('electron', args)

  electronProcess?.stdout?.on('data', data => {
    console.log(chalk.blueBright('[Electron] ') + chalk.white(data.toString()))
  })

  electronProcess?.stderr?.on('data', data => {
    console.log(chalk.redBright('[Electron] ') + chalk.white(data.toString()))
  })
}
Example #20
Source File: utils.ts    From airnode with MIT License 6 votes vote down vote up
runCommandInBackground = (command: string) => {
  logger.log(`Running background command:\n${command}`);
  return spawn(command, {
    detached: true,
    shell: true,
  });
}
Example #21
Source File: skeleton.ts    From aurora-relayer with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
protected async _banIP(ip: string, reason?: string): Promise<void> {
    if (!ip) return;
    blacklist('IPs').add(ip);
    if (
      process.env.CF_API_TOKEN &&
      process.env.CF_ACCOUNT_ID &&
      process.env.CF_LIST_ID
    ) {
      const subprocess = spawn(
        '/srv/aurora/relayer/util/ban/ban', // FIXME: don't use absolute path
        [ip, reason || ''],
        {
          shell: false,
          detached: true,
          stdio: 'ignore',
          timeout: 60 * 1000,
          env: process.env,
        }
      );
      subprocess.unref();
    }
  }
Example #22
Source File: run.ts    From backstage with Apache License 2.0 6 votes vote down vote up
// Runs a child command, returning a promise that is only resolved if the child exits with code 0.
export async function run(
  name: string,
  args: string[] = [],
  options: SpawnOptionsPartialEnv = {},
) {
  const { stdoutLogFunc, stderrLogFunc } = options;
  const env: NodeJS.ProcessEnv = {
    ...process.env,
    FORCE_COLOR: 'true',
    ...(options.env ?? {}),
  };

  const stdio = [
    'inherit',
    stdoutLogFunc ? 'pipe' : 'inherit',
    stderrLogFunc ? 'pipe' : 'inherit',
  ] as ('inherit' | 'pipe')[];

  const child = spawn(name, args, {
    stdio,
    shell: true,
    ...options,
    env,
  });

  if (stdoutLogFunc && child.stdout) {
    child.stdout.on('data', stdoutLogFunc);
  }
  if (stderrLogFunc && child.stderr) {
    child.stderr.on('data', stderrLogFunc);
  }

  await waitForExit(child, name);
}
Example #23
Source File: server.ts    From plugin-vscode with Apache License 2.0 6 votes vote down vote up
export function spawnStdioServer(ballerinaHome: string): ChildProcess {
    let cmd;
    const cwd = path.join(ballerinaHome, "lib", "tools", "lang-server", "launcher");
    const args: string[] = [];
    if (process.platform === "win32") {
        cmd = path.join(cwd, "language-server-launcher.bat");
    } else {
        cmd = "sh";
        args.push(path.join(cwd, "language-server-launcher.sh"));
    }

    // always run with experimental features enabled
    args.push("--experimental");

    if (LS_DEBUG) {
        args.push("--debug");
    }
    if (LS_CUSTOM_CLASSPATH) {
        args.push("--classpath", LS_CUSTOM_CLASSPATH);
    }
    return spawn(cmd, args, { cwd });
}
Example #24
Source File: child.process.ts    From diablo2 with MIT License 6 votes vote down vote up
export async function run(
  cmd: string,
  args: string[],
): Promise<{ cmd: string; args: string[]; exitCode: number; stdout: string; stderr: string; duration: number }> {
  const startTime = Date.now();

  const child = spawn(cmd, args);

  const stdout: string[] = [];
  const stderr: string[] = [];

  child.stdout.on('data', (chunk: string) => stdout.push(chunk));
  child.stderr.on('data', (chunk: string) => stderr.push(chunk));

  return new Promise((resolve) => {
    child.on('exit', (exitCode: number) => {
      resolve({
        cmd,
        args,
        exitCode,
        stdout: stdout.join('').trim(),
        stderr: stderr.join('').trim(),
        duration: Date.now() - startTime,
      });
    });
  });
}
Example #25
Source File: server.ts    From omegga with ISC License 6 votes vote down vote up
// forcibly kills the server
  stop() {
    if (!this.#child) {
      Logger.verbose('Cannot stop server as no subprocess exists');
      return;
    }

    Logger.verbose('Forcibly stopping server');
    // kill the process
    this.#child.kill('SIGINT');

    // ...kill it again just to make sure it's dead
    spawn('kill', ['-9', this.#child.pid + '']);
  }
Example #26
Source File: stream.example.ts    From listr2 with MIT License 6 votes vote down vote up
async function main (): Promise<void> {
  let task: Listr<Ctx>

  logger.start('Example output from a task.')

  // eslint-disable-next-line prefer-const
  task = new Listr<Ctx>(
    [
      {
        title: 'This task will execute.',
        task: async (): Promise<Readable> => {
          return spawn('ls').stdout
        },
        options: {
          persistentOutput: true
        }
      }
    ],
    { concurrent: false }
  )

  try {
    const context = await task.run()

    logger.success(`Context: ${JSON.stringify(context)}`)
  } catch (e: any) {
    logger.fail(e)
  }
}
Example #27
Source File: webscraper.test.ts    From crossfeed with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
jest.mock('child_process', () => ({
  spawn: jest.fn().mockImplementationOnce(() => ({
    status: 0,
    stderr: Readable.from(['scrapy output']),
    stdout: Readable.from([
      `
line with no database output
database_output: {"body": "abc", "headers": [{"a": "b", "c": "d"}], "status": 200, "url": "https://docs.crossfeed.cyber.dhs.gov", "domain_name": "docs.crossfeed.cyber.dhs.gov"}
database_output: {"s3_key": "1de6816e1b0d07840082bed89f852b3f10688a5df6877a97460dbc474195d5dd", "status": 200, "url": "https://docs.crossfeed.cyber.dhs.gov/scans/", "domain_name": "docs.crossfeed.cyber.dhs.gov"}
database_output: {"s3_key": "6a2946030f804a281a0141397dbd948d7cae4698118bffd1c58e6d5f87480435", "status": 200, "url": "https://docs.crossfeed.cyber.dhs.gov/contributing/", "domain_name": "docs.crossfeed.cyber.dhs.gov"}
database_output: {"s3_key": "d8f190dfeaba948e31fc26e3ab7b7c774b1fbf1f6caac535e4837595eadf4795", "status": 200, "url": "https://docs.crossfeed.cyber.dhs.gov/usage/", "domain_name": "docs.crossfeed.cyber.dhs.gov"}
database_output: {"body": "abc", "headers": [{"a": "b", "c": "d"}], "status": 200, "url": "https://docs.crossfeed.cyber.dhs.gov", "domain_name": "docs.crossfeed.cyber.dhs.gov"}
database_output: {"s3_key": "226706ff585e907aa977323c404b9889f3b2e547d134060ed57fda2e2f1b9860", "status": 200, "url": "https://docs.crossfeed.cyber.dhs.gov/contributing/deployment/", "domain_name": "docs.crossfeed.cyber.dhs.gov"}
database_output: {"s3_key": "e1448fa789c02ddc90a37803150923359a4a21512e1737caec52be53ef3aa3b5", "status": 200, "url": "https://docs.crossfeed.cyber.dhs.gov/contributing/architecture/", "domain_name": "docs.crossfeed.cyber.dhs.gov"}
database_output: {"s3_key": "3091ca75bf2ee1e0bead7475adb2db8362f96b472d220fd0c29eaac639cdf37f", "status": 200, "url": "https://docs.crossfeed.cyber.dhs.gov/usage/customization/", "domain_name": "docs.crossfeed.cyber.dhs.gov"}
line with no database output {}
database_output: {"s3_key": "dd7e7e51a4a094e87ad88756842854c2d878ac55fb908035ddaf229c5568fa1a", "status": 200, "url": "https://docs.crossfeed.cyber.dhs.gov/usage/administration/", "domain_name": "docs.crossfeed.cyber.dhs.gov"}
database_output: {"s3_key": "afb6378d30bd1b43d86be5d1582d0e306ba6c9dd2c60f0dcbb1a3837b34cbe59", "status": 400, "url": "https://docs.crossfeed.cyber.dhs.gov/contributing/setup/", "domain_name": "docs.crossfeed.cyber.dhs.gov"}
database_output: {"s3_key": "afb6378d30bd1b43d86be5d1582d0e306ba6c9dd2c60f0dcbb1a3837b34cbe60", "status": 200, "url": "https://unrelated-url.cyber.dhs.gov/contributing/setup/", "domain_name": "unrelated-url.cyber.dhs.gov"}
`
    ])
  }))
}));
Example #28
Source File: init.ts    From engine with MIT License 6 votes vote down vote up
init: producer = ({
  _spawn = spawn,
  trigger = observe.test.triggers.init,
  commandPath = get.config.commandPath,
}: props) => {
  if (!trigger) {
    return;
  }
  spawn(
    `cd ${commandPath.value()} && jest --clearCache && jest --config ./jest.config.js --runTestsByPath ./src/**/*`
  );
}
Example #29
Source File: process.ts    From cli with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @private
 * @param {string} command The command to run
 * @param {string[]} args List of string arguments
 * @param {SpawnOptions} [options={}]
 * @returns {Promise<number>} A promise of the the child process exit code
 */
export function spawnProcess(
  command: string,
  args: string[],
  options: SpawnOptions = {}
): Promise<number> {
  return new Promise((resolve, reject) => {
    spawn(command, args, {
      stdio: ['inherit', 'inherit', 'inherit'],
      ...options,
    }).on('close', (code) => {
      if (code !== 0) {
        // TODO: inject logger decorator so this util method can log
        // this.debug(
        //   `Following command has failed: ${command} ${args.join(' ')}`
        // );

        // Any error message triggered by the execution of the subprocess will be
        // displayed since the terminal is shared by both parent and child processes.
        // So no need to bubble up the error.
        reject(code);
      } else {
        resolve(0);
      }
    });
  });
}