当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript child_process.spawn函数代码示例

本文整理汇总了TypeScript中child_process.spawn函数的典型用法代码示例。如果您正苦于以下问题:TypeScript spawn函数的具体用法?TypeScript spawn怎么用?TypeScript spawn使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了spawn函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: start

    start() {
        let projectPath: string = "";
        if (vscode.workspace.rootPath !== undefined) {
            projectPath = path.join(vscode.workspace.rootPath);
        } else {
            const savedFiles: vscode.TextDocument[] = vscode.workspace.textDocuments.filter((value) => {
                return value.uri.scheme === 'file';
            });
            if (savedFiles.length > 0) {
                projectPath = path.dirname(savedFiles[0].fileName);
            } else {
                // Bail out, lets use our extensionPath as projectPath
                projectPath = vscode.extensions.getExtension("mjmcloug.vscode-elixir").extensionPath;
            }
        }
        const optionsWin = { cwd: projectPath, windowsVerbatimArguments: true, stdio: 'pipe' };
        const optionsUnix = { cwd: projectPath, stdio: 'pipe' };
        if (process.platform === 'win32') {
            this.p = cp.spawn('cmd', ['/s', '/c', '"' + [this.command].concat(this.args).concat(this.env).join(' ') + '"'], optionsWin);
        }
        else {
            this.p = cp.spawn(this.command, this.args.concat(this.env), optionsUnix);
        }
        console.log('[vscode-elixir] server started', this.p);
        this.p.on('message', (message) => {
            console.log('message', message);
        });
        this.p.on('error', (error) => {
            console.log('[vscode-elixir]', error.toString());
        });
        this.p.on('close', (exitCode) => {
            console.log('[vscode-elixir] exited', exitCode);
        });
        this.p.stdout.on('data', (chunk) => {
            if (chunk.indexOf(`END-OF-${this.lastRequestType}`) > -1) {
                const chunkString: string = chunk.toString();
                const splitStrings: string[] = chunkString.split(`END-OF-${this.lastRequestType}`);
                const result = (this.buffer + splitStrings[0]).trim();
                this.resultCallback(result);
                this.buffer = '';
                this.busy = false;
            } else {
                this.buffer += chunk.toString();
            }
        });
        this.p.stderr.on('data', (chunk: Buffer) => {
            const errorString = chunk.toString();
            if (!errorString.startsWith('Initializing')) {
                console.log('[vscode-elixir] error: arboting command', chunk.toString());
                //TODO: this could be handled better.
                if (this.resultCallback) {
                    this.resultCallback('');
                }
                this.busy = false;

            } else {
                console.log('[vscode-elixir]', chunk.toString());
                this.ready = true;
            }
        });
    }
开发者ID:Fahrradflucht,项目名称:vscode-elixir,代码行数:61,代码来源:elixirServer.ts

示例2: create_machine

    static create_machine(gce_project_id: string, cb: (exit_status: number, mach: Machine)=>void): void
    {
        var machine_name: string = "cloud-aln-" + util.random_string(16).toLowerCase();

        var create_args: Array<string> = [];
        if (gce_project_id)
            create_args = ["create", "--driver", "google", "--google-project", gce_project_id, "--google-zone", "us-central1-b", "--google-machine-type", "n1-highcpu-32", "--google-disk-size", "40", "--google-preemptible", machine_name];
        else
            create_args = ["create", "--driver", "virtualbox", machine_name];

        var create_machine_proc: child_process.ChildProcess = child_process.spawn("docker-machine", create_args);

        create_machine_proc.stdout.on("data", function(data: Buffer)
        {
            process.stdout.write(data);
        });

        create_machine_proc.stderr.on("data", function(data: Buffer)
        {
            process.stderr.write(data);
        });

        create_machine_proc.on("close", function(exit_code: number)
        {
            if (exit_code)
            {
                Machine.destroy_machine_by_name(machine_name, function(exit_status: number)
                {
                    if (exit_status)
                        console.error("Destroying machine FAILED: " + exit_status);
                    cb(exit_code, null);
                });
            }
            else
            {
                var env_data: string = "";
                var get_machine_env_proc = child_process.spawn("docker-machine", ["env", machine_name]);
                get_machine_env_proc.stdout.on("data", function(data: Buffer)
                {
                    env_data += data.toString("utf8");
                });

                get_machine_env_proc.on("close", function(exit_code: number)
                {
                    if (exit_code)
                    {
                        Machine.destroy_machine_by_name(machine_name, function(exit_status: number)
                        {
                            if (exit_status)
                                console.error("Destroying machine FAILED: " + exit_status);
                            cb(exit_code, null);
                        });
                    }
                    else
                    {
                        var host_res = new RegExp("export DOCKER_HOST=\"tcp://([^\"]+)\"").exec(env_data);
                        var cert_path_res = new RegExp("export DOCKER_CERT_PATH=\"([^\"]+)\"").exec(env_data);

                        if (!host_res || host_res.length != 2 || !cert_path_res || cert_path_res.length != 2)
                        {
                            console.error("Could not parse docker machine environment");
                            Machine.destroy_machine_by_name(machine_name, function(exit_status: number)
                            {
                                if (exit_status)
                                    console.error("Destroying machine FAILED: " + exit_status);
                                cb(-1, null);
                            });

                        }
                        else
                        {
                            cb(0, new Machine(machine_name, host_res[1], cert_path_res[1], gce_project_id.length ? 32 : 2));
                        }
                    }
                });
            }
        });
    }
开发者ID:statgen,项目名称:cloud-align,代码行数:78,代码来源:machine.ts

示例3: main

export function main(argv: string[]): TPromise<void> {
	let args: ParsedArgs;

	try {
		args = parseCLIProcessArgv(argv);
	} catch (err) {
		console.error(err.message);
		return TPromise.as(null);
	}

	if (args.help) {
		console.log(buildHelpMessage(product.nameLong, product.applicationName, pkg.version));
	} else if (args.version) {
		console.log(`${pkg.version}\n${product.commit}\n${process.arch}`);
	} else if (shouldSpawnCliProcess(args)) {
		const mainCli = new TPromise<IMainCli>(c => require(['vs/code/node/cliProcessMain'], c));
		return mainCli.then(cli => cli.main(args));
	} else {
		const env = assign({}, process.env, {
			// this will signal Code that it was spawned from this module
			'VSCODE_CLI': '1',
			'ELECTRON_NO_ATTACH_CONSOLE': '1'
		});

		delete env['ELECTRON_RUN_AS_NODE'];

		if (args.verbose) {
			env['ELECTRON_ENABLE_LOGGING'] = '1';
		}

		// If we are started with --wait create a random temporary file
		// and pass it over to the starting instance. We can use this file
		// to wait for it to be deleted to monitor that the edited file
		// is closed and then exit the waiting process.
		let waitMarkerFilePath: string;
		if (args.wait) {
			let waitMarkerError: Error;
			const randomTmpFile = paths.join(os.tmpdir(), Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 10));
			try {
				fs.writeFileSync(randomTmpFile, '');
				waitMarkerFilePath = randomTmpFile;
				argv.push('--waitMarkerFilePath', waitMarkerFilePath);
			} catch (error) {
				waitMarkerError = error;
			}

			if (args.verbose) {
				if (waitMarkerError) {
					console.error(`Failed to create marker file for --wait: ${waitMarkerError.toString()}`);
				} else {
					console.log(`Marker file for --wait created: ${waitMarkerFilePath}`);
				}
			}
		}

		const options = {
			detached: true,
			env
		};

		if (!args.verbose) {
			options['stdio'] = 'ignore';
		}

		const child = spawn(process.execPath, argv.slice(2), options);

		if (args.verbose) {
			child.stdout.on('data', (data: Buffer) => console.log(data.toString('utf8').trim()));
			child.stderr.on('data', (data: Buffer) => console.log(data.toString('utf8').trim()));
		}

		if (args.verbose) {
			return new TPromise<void>(c => child.once('exit', () => c(null)));
		}

		if (args.wait && waitMarkerFilePath) {
			return new TPromise<void>(c => {

				// Complete when process exits
				child.once('exit', () => c(null));

				// Complete when wait marker file is deleted
				whenDeleted(waitMarkerFilePath).done(c, c);
			});
		}
	}

	return TPromise.as(null);
}
开发者ID:SeanKilleen,项目名称:vscode,代码行数:89,代码来源:cli.ts

示例4: runRlsViaRustup

export async function runRlsViaRustup(env: any, config: RustupConfig): Promise<child_process.ChildProcess> {
    await ensureToolchain(config);
    await checkForRls(config);
    return child_process.spawn(config.path, ['run', config.channel, 'rls'], { env });
}
开发者ID:digitaltoad,项目名称:dotfiles,代码行数:5,代码来源:rustup.ts

示例5: async

  watcher.on(actions.relaunch, async (store, action) => {
    const rs = store.getState();
    const pkg = rs.broth.packages["itch-setup"];
    if (pkg.stage !== "idle") {
      logger.warn(`itch-setup: wanted pkg stage idle but got '${pkg.stage}'`);
      return;
    }

    const prefix = pkg.versionPrefix;
    if (!prefix) {
      logger.warn(`itch-setup: no prefix (not installed yet?)`);
      return;
    }

    const command = ospath.join(prefix, "itch-setup");
    const args: string[] = [
      "--appname",
      rs.system.appName,
      "--relaunch",
      "--relaunch-pid",
      `${process.pid}`,
    ];

    const stdio: any[] = ["ignore", "ignore", "ignore"];
    const logPath = relaunchLogPath();
    try {
      fs.mkdirSync(dirname(logPath));
    } catch (e) {}
    try {
      fs.unlinkSync(logPath);
    } catch (e) {}

    let out = -1;
    let err = -1;
    try {
      if (fs.existsSync(logPath)) {
        fs.unlinkSync(logPath);
      }
      out = fs.openSync(logPath, "a");
      stdio[1] = out;
      err = fs.openSync(logPath, "a");
      stdio[2] = err;
    } catch (e) {
      logger.warn(`Could not set up stdout/stderr for relaunch: ${e.stack}`);
      if (out != -1) {
        fs.closeSync(out);
      }
      if (err != -1) {
        fs.closeSync(err);
      }
    }
    const child = childProcess.spawn(command, args, {
      stdio,
      detached: true,
    });
    child.unref();

    for (let i = 0; i < 30; i++) {
      try {
        const file = fs.readFileSync(logPath, { encoding: "utf8" });
        const tokens = file.split("\n");
        for (const tok of tokens) {
          try {
            const msg = JSON.parse(tok) as ISM;
            if (msg.type === "ready-to-relaunch") {
              logger.info(`itch-setup is ready to relaunch!`);
              store.dispatch(actions.quit({}));
              return;
            }
          } catch (e) {
            // ignore
          }
        }
      } catch (e) {
        logger.warn(`While polling itch-setup log: ${e.stack}`);
      }
      await delay(250);
    }
  });
开发者ID:itchio,项目名称:itch,代码行数:79,代码来源:self-update.ts

示例6: stop

 public stop() {
     cp.spawn('dcd-client', ['--shutdown']);
 }
开发者ID:LaurentTreguier,项目名称:dlang-vscode,代码行数:3,代码来源:server.ts

示例7: kill

 public kill() {
     console.log("KILL:", this.etcdir)
     this.etcd.kill('SIGTERM')
     cp.spawn("rm", ["-r", this.etcdir])
 }
开发者ID:protonet,项目名称:certor,代码行数:5,代码来源:etcd_daemon.ts

示例8: spawn

 const runUpdater = (args: string[], done: any) => {
     return spawn(updateExe, args, { detached: true }).on('close', done);
 };
开发者ID:JimiC,项目名称:evetron,代码行数:3,代码来源:squirrelHandler.ts

示例9: Promise

		return new Promise((resolve, reject) => {
			token.onCancellationRequested(() => this.cancel());

			const rgArgs = getRgArgs(options);

			const cwd = options.folder.fsPath;

			const escapedArgs = rgArgs
				.map(arg => arg.match(/^-/) ? arg : `'${arg}'`)
				.join(' ');
			this.outputChannel.appendLine(`rg ${escapedArgs}\n - cwd: ${cwd}\n`);

			this.rgProc = cp.spawn(rgDiskPath, rgArgs, { cwd });

			this.rgProc.on('error', e => {
				console.log(e);
				reject(e);
			});

			let leftover = '';
			this.collectStdout(this.rgProc, (err, stdout, last) => {
				if (err) {
					reject(err);
					return;
				}

				// Mac: uses NFD unicode form on disk, but we want NFC
				const normalized = leftover + (isMac ? normalizeNFC(stdout) : stdout);
				const relativeFiles = normalized.split('\n');

				if (last) {
					const n = relativeFiles.length;
					relativeFiles[n - 1] = relativeFiles[n - 1].trim();
					if (!relativeFiles[n - 1]) {
						relativeFiles.pop();
					}
				} else {
					leftover = relativeFiles.pop();
				}

				if (relativeFiles.length && relativeFiles[0].indexOf('\n') !== -1) {
					reject(new Error('Splitting up files failed'));
					return;
				}

				relativeFiles.forEach(relativeFile => {
					progress.report(relativeFile);
				});

				if (last) {
					if (this.isDone) {
						resolve();
					} else {
						// Trigger last result
						this.rgProc = null;
						if (err) {
							reject(err);
						} else {
							resolve();
						}
					}
				}
			});
		});
开发者ID:burhandodhy,项目名称:azuredatastudio,代码行数:64,代码来源:ripgrepFileSearch.ts

示例10: spawn

import * as logger from './logger';
import { attach }  from 'neovim';
import { spawn }   from 'child_process';
import * as _      from 'lodash';
import * as fs     from 'fs';

const nvim_proc = spawn('nvim', ['--embed']);

const nvim = attach({ proc: nvim_proc });
(async function() {
  const data = await nvim.request('vim_get_api_info');
  logger.log(data);
  const funcs = data[1].functions;
  _.sortBy(funcs, 'name');
  const wstream = fs.createWriteStream('api.md');
  wstream.write('| Function name | Parameters | Return |\n');
  wstream.write('| ------------- | ---------- | ------ |\n');
  for (let fdesc of funcs) {
    const params = fdesc.parameters
      .map((param) => `*${param[0]}* ${param[1]}`)
      .join(', ');

    wstream.write(
      `| ${fdesc.name} | ${params} | ${fdesc.return_type} |\n`
    );
  }
  wstream.end(null, null, () =>
    process.exit()
  );
})();
开发者ID:duskpoet,项目名称:chrome-debugger-vim,代码行数:30,代码来源:api.ts


注:本文中的child_process.spawn函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。