child_process#exec TypeScript Examples

The following examples show how to use child_process#exec. 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: file.utils.ts    From WowUp with GNU General Public License v3.0 7 votes vote down vote up
function executeWinRm(path: string) {
  return new Promise<void>((resolve, reject) => {
    exec(`rmdir "${path}" /s /q`, (err, stdout, stderr) => {
      if (err || stdout.length || stderr.length) {
        log.error("rmdir fallback failed", err, stdout, stderr);
        return reject(new Error("rmdir fallback failed"));
      }
      resolve(undefined);
    });
  });
}
Example #2
Source File: utils.ts    From checkov-vscode with Apache License 2.0 7 votes vote down vote up
asyncExec = async (commandToExecute: string, options: ExecOptions = {}): Promise<ExecOutput> => {
    const defaultOptions: ExecOptions = { maxBuffer: 1024 * 1000 };
    return new Promise((resolve, reject) => {
        exec(commandToExecute, { ...defaultOptions, ...options }, (err, stdout, stderr) => {
            if (err) { return reject(err); }
            resolve([stdout, stderr]);
        });
    });
}
Example #3
Source File: test-util.ts    From attranslate with MIT License 7 votes vote down vote up
export function runCommand(cmd: string, pwd?: string): Promise<string> {
  cmd = buildFinalCommand(cmd, pwd);
  console.log(`Run command \'${cmd}\'`);
  return new Promise((resolve, reject) => {
    exec(cmd, (error, stdout, stderr) => {
      console.log(stdout);
      if (error) {
        console.error(stderr);
        console.error(`Failed to execute \'${cmd}\'. See the output above.`);
        reject(stdout + stderr);
      } else {
        resolve(stdout);
      }
    });
  });
}
Example #4
Source File: utils.ts    From vsc-markdown-image with MIT License 7 votes vote down vote up
function noticeComment(context: vscode.ExtensionContext) {
    let notice = context.globalState.get('notice');
    let usetimes: number = context.globalState.get('usetimes') || 0;
    if (!notice && usetimes > 100) {
        confirm(locale['like.extension'], [locale['like.ok'], locale['like.no'], locale['like.later']])
            .then((option) => {
                switch(option) {
                    case locale['like.ok']:
                        exec(`${getOpenCmd()} https://marketplace.visualstudio.com/items?itemName=hancel.markdown-image`);
                        context.globalState.update('notice', true);
                        break;
                    case locale['like.no']:
                        context.globalState.update('notice', true);
                        break;
                    case locale['like.later']:
                        usetimes = 50;
                        context.globalState.update('usetimes', usetimes);
                        context.globalState.update('notice', false);
                        break;
                }
            })
            .catch(e => console.debug(e));
    } else if(!notice) {
        context.globalState.update('usetimes', ++usetimes);
    }
}
Example #5
Source File: utils.ts    From vue3-gettext with MIT License 7 votes vote down vote up
export function execShellCommand(cmd: string) {
  return new Promise((resolve) => {
    exec(cmd, (error, stdout, stderr) => {
      if (error) {
        console.warn(error);
      }
      resolve(stdout ? stdout : stderr);
    });
  });
}
Example #6
Source File: utils.ts    From shadowsocks-electron with GNU General Public License v3.0 7 votes vote down vote up
checkEnvFiles = (args: {_path: string, isDir: boolean, checkEmpty?: boolean, exec?: () => void}[]): void => {
  const check = function (params: {_path: string, isDir: boolean, checkEmpty?: boolean, exec?: () => void}) {
    if (!fs.existsSync(params._path)) {
      if (params.isDir) {
        fs.mkdirSync(params._path);
        params.exec && params.exec();
      } else {
        fs.closeSync(fs.openSync(params._path, 'w'));
      }
    } else {
      if (params?.checkEmpty) {
        if (fs.readdirSync(params._path).length === 0) {
          params.exec && params.exec();
        }
      }
    }
  };

  args.forEach(check);
}
Example #7
Source File: utils.ts    From server with Apache License 2.0 7 votes vote down vote up
public async processItemAction(actionIdentifier: string, event: string, item: Item, newParent: string, newName: string, newValues: any, newChannels:any, isImport: boolean) {
        const mng = ModelsManager.getInstance().getModelManager(this.#context.getCurrentUser()!.tenantId)

        let action  = mng.getActions().find(act => act.identifier === actionIdentifier)
        if (!action) {
            throw new Error('Failed to find action by identifier: ' + actionIdentifier + ', tenant: ' + mng.getTenantId())
        }

        const context = this.#context
        return await processActions(mng, [action], { Op: Op,
            event: event,
            user: context.getCurrentUser()?.login,
            roles: context.getUser()?.getRoles(),
            utils: new ActionUtils(context),
            system: { AdmZip, fs, exec, awaitExec, fetch, URLSearchParams, mailer, http, https, http2 },
            isImport: isImport, 
            item: makeItemProxy(item), values: newValues, channels: newChannels, name: newName, parent: newParent,
            models: { 
                item: makeModelProxy(Item.applyScope(context), makeItemProxy),  
                itemRelation: makeModelProxy(ItemRelation.applyScope(context), makeItemRelationProxy),  
                lov: makeModelProxy(LOV.applyScope(context), makeLOVProxy),
                Item,
                ItemRelation
            } 
        })
    }
Example #8
Source File: queryTest.ts    From anchorcli with Apache License 2.0 6 votes vote down vote up
async function cli(args: string[]): Promise<CliResult> {
  
  return new Promise(resolve => {  
    exec(
      `${cliPath} ${args.join(' ')}`,
      {}, 
      (error, stdout, stderr) => {resolve({        
        error,
        stdout,
        stderr 
      })
    })
  })
}
Example #9
Source File: exec-process.ts    From nx-plugins with MIT License 6 votes vote down vote up
export function execProcess(
  command: string,
  { env = process.env, ...options }: ExecOptions = {},
): Observable<ProcessOutput> {
  return new Observable<ProcessOutput>((observer) => {
    const child = exec(command, {
      ...options,
      env: processEnv(env),
    });
    const processExitListener = () => {
      observer.complete();
      child.kill();
    };

    process.on('exit', processExitListener);
    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 #10
Source File: run_solution.ts    From CodePal with GNU General Public License v3.0 6 votes vote down vote up
runTests = async (
    runCommand: string,
    testsFolderPath: string,
    stderrFilePath: string
): Promise<any> => {
    try {
        return new Promise(async (resolve, reject) => {
            exec(runCommand, async (error: any, stdout: any, stderr: any) => {
                if (error) {
                    if(tle.tleFlag) {
                        return;
                    }
                    console.log(`Runtime Error: ${error}`);
                    await reportError(error.message, "Run Time", testsFolderPath);
                    reject(error.message);
                    return;
                }
                if (stderr) {
                    console.log(`stderr: ${stderr}`);
                    fs.writeFileSync(stderrFilePath, stderr, (err: any) => {
                        if (err) {
                            vscode.window.showErrorMessage("Could not write stderr.");
                        }
                    });
                } else if (fs.existsSync(stderrFilePath)) {
                    fs.unlinkSync(stderrFilePath, (err: any) => {
                        console.log(err);
                    });
                }

                resolve(stdout);
            });
        });
    } catch (err) {
        console.log("Run time error: " + err);
    }
}
Example #11
Source File: functions.ts    From KryPtoN-WhatsApp-Bot with GNU General Public License v3.0 6 votes vote down vote up
term = (param: string) => new Promise((resolve, reject) => {
    console.log('Run terminal =>', param)
    exec(param, (error: any, stdout: string, stderr: string) => {
        if (error) {
            console.log(error.message)
            resolve(error.message)
        }
        if (stderr) {
            console.log(stderr)
            resolve(stderr)
        }
        console.log(stdout)
        resolve(stdout)
    })
})
Example #12
Source File: iDeviceConnections.ts    From iOSreExtension with Apache License 2.0 6 votes vote down vote up
public ensureiProxy(element: iDeviceItem) {
        if (iDeviceNodeProvider.iProxyPool[element.udid] === undefined) {
            let dp = (element).iSSH_devicePort;
            let mp = (element).iSSH_mappedPort;
            console.log("[*] Starting iProxy " + mp + ":" + dp + " -u " + element.udid + " &");
            let execObject = exec("iproxy " + mp + ":" + dp + " -u " + element.udid + "", (err, stdout, stderr) => {
                console.log(stdout + stderr);
                this.refresh();
            });
            iDeviceNodeProvider.iProxyPool[element.udid] = execObject;
            this.refresh();
            ApplicationNodeProvider.nodeProvider.refresh();
            FileSystemNodeProvider.nodeProvider.refresh();
        }
    }
Example #13
Source File: files.ts    From ow-mod-manager with MIT License 6 votes vote down vote up
export function openDirectory(directoryPath: string) {
  if (!directoryPath) {
    throw new Error(modsText.modPathNotDefinedError);
  }
  if (!fs.existsSync(directoryPath)) {
    throw new Error(modsText.openNonExistingDirectoryError);
  }

  exec(`start "open directory" "${path.resolve(directoryPath)}"`);
}
Example #14
Source File: UserSystemFunctions.ts    From Templater with GNU Affero General Public License v3.0 6 votes vote down vote up
constructor(app: App, private plugin: TemplaterPlugin) {
        if (
            Platform.isMobileApp ||
            !(app.vault.adapter instanceof FileSystemAdapter)
        ) {
            this.cwd = "";
        } else {
            this.cwd = app.vault.adapter.getBasePath();
            this.exec_promise = promisify(exec);
        }
    }
Example #15
Source File: upgrade.ts    From Adachi-BOT with MIT License 6 votes vote down vote up
/* 命令执行 */
async function execHandle( command: string ): Promise<string> {
	return new Promise( ( resolve, reject ) => {
		exec( command, ( error, stdout, stderr ) => {
			if ( error ) {
				reject( error );
			} else {
				resolve( stdout );
			}
		} )
	} )
}
Example #16
Source File: docker.ts    From vscode-windows-terminal with MIT License 6 votes vote down vote up
export function runDockerCommand(command: string): Promise<string> {
  return new Promise<string>((resolve, reject) => {
    exec(`docker ${command}`, (err, stdout, stderr) => {
      if (err) {
        reject(err);
      }
      resolve(stdout.trim());
    });
  });
}
Example #17
Source File: setup.ts    From amplication with Apache License 2.0 6 votes vote down vote up
async function runFunction(task: Task): Promise<string> {
  spinner.start(`Executing ${task.label}` + "\n");
  return new Promise((resolve, reject) => {
    exec(task.command, (error, stdout, stderr) => {
      error && reject(error);
      if (stdout) {
        spinner.succeed(`Finished ${task.label}`);
        stdout && resolve(task.label);
      }
    });
  });
}
Example #18
Source File: terraform-fmt.ts    From airnode with MIT License 6 votes vote down vote up
exec(BINARY_TEST, (err, _stdout, _stderr) => {
  if (err) {
    logger.log('Missing Terraform binary, skipping formatting.');
    exit();
  }

  if (command === 'check') {
    exec(CMD_CHECK, (err, stdout, stderr) => {
      failOnError('Failed to list Terraform formatting issues', err, stderr);

      if (stdout) {
        logger.log('Found unformatted TF files:');
        logger.log(stdout);
        // We have unformatted files, we have to fail
        exit(EC_FORMATTING);
      }

      logger.log('All TF files formatted correctly!');
      exit();
    });
  }

  if (command === 'write') {
    exec(CMD_WRITE, (err, stdout, stderr) => {
      failOnError('Failed to correct Terraform formatting issues', err, stderr);

      if (stdout) {
        logger.log('Fixed formatting of the following TF files:');
        logger.log(stdout);
      } else {
        logger.log('All TF files already formatted correctly, nothing to do');
      }
      exit();
    });
  }
});
Example #19
Source File: schedule.ts    From ql with MIT License 6 votes vote down vote up
run = async () => {
  const cronService = Container.get(CronService);
  const cronDb = cronService.getDb();

  cronDb
    .find({})
    .sort({ created: 1 })
    .exec((err, docs) => {
      if (err) {
        Logger.error(err);
        process.exit(1);
      }

      if (docs && docs.length > 0) {
        for (let i = 0; i < docs.length; i++) {
          const task = docs[i];
          const _schedule = task.schedule && task.schedule.split(' ');
          if (
            _schedule &&
            _schedule.length > 5 &&
            task.status !== CrontabStatus.disabled &&
            !task.isDisabled
          ) {
            schedule.scheduleJob(task.schedule, function () {
              let command = task.command as string;
              if (!command.includes('task ') && !command.includes('ql ')) {
                command = `task ${command}`;
              }
              exec(command);
            });
          }
        }
      }
    });
}
Example #20
Source File: build.test.ts    From foca with MIT License 6 votes vote down vote up
function testFile(filename: string, expectCode: number) {
  return new Promise((resolve) => {
    const child = exec(`node ${filename}`);
    child.on('exit', (code) => {
      try {
        expect(code).toBe(expectCode);
      } finally {
        resolve(code);
      }
    });
  });
}
Example #21
Source File: build.ts    From js-client with MIT License 6 votes vote down vote up
execAsync = (command: string): Promise<string> =>
	new Promise((resolve, reject) => {
		exec(command, (err, stdout, stderr) => {
			if (err) {
				if (stdout) (err as any).logs = stdout;
				reject(err);
			} else resolve(stdout);
		});
	})
Example #22
Source File: PackageJsonGenerator.ts    From nodemaker with MIT License 6 votes vote down vote up
/**Insert the new node credential at their appropriate location in `package.json`.*/
  private insertCredentialInPackageJson() {
    const command = this.formatCommand(`
    gen updateCredentialPackageJson
      --serviceCredential ${this.getServiceCredentialName(this.metaParameters)}
      --credentialSpot ${this.findCredentialSpot()}
    `);

    exec(command);
  }
Example #23
Source File: remote.ts    From portable with Apache License 2.0 6 votes vote down vote up
private _executeCommand(
            program: string,
            args: string,
            envDict?: {}
        ) : Promise<string>
    {
        let options: Options = {};
        options.timeout = 20 * 1000;
        if (_.isArray(args)) {
            args = args.join(" ");
        }
        let cmd = program;
        if (args && args.length > 0) {
            cmd = program + " " + args;
        }
        if (envDict) {
            envDict = _.defaults(envDict, process.env);
            options.env = envDict;
        }

        this.logger.info("[_executeCommand] running: %s, options:", cmd, options);
        return Promise.construct((resolve, reject) => {
            exec(cmd, options, (error, stdout, stderr) => {
            if (error) {
                this.logger.error("[_executeCommand] failed: %s", error.message);
                this.logger.error("[_executeCommand] cmd: %s", error.cmd);
                this.logger.error("[_executeCommand] killed: %s", error.killed);
                this.logger.error("[_executeCommand] signal: %s", error.signal);
                this.logger.error("[_executeCommand] code: %s", error.code);
                this.logger.error("[_executeCommand] stdout: %s", stdout);
                this.logger.error("[_executeCommand] stderr: %s", stderr);
                reject(error);
            } else {
                this.logger.info("[_executeCommand] result: ", stdout);
                resolve(stdout);
            }
            });
        });
    }
Example #24
Source File: exec-async.ts    From metroline with GNU General Public License v3.0 6 votes vote down vote up
export function execAsync(cmd: string, options?: ExecOptions): Promise<string> {
  return new Promise((resolve, reject) => {
    exec(cmd, options, (error, stdout, stderr) => {
      if (error) {
        reject(new ExecError(error, stdout, stderr));
      }
      resolve(stdout);
    });
  });
}
Example #25
Source File: typescript-installer.ts    From DefinitelyTyped-tools with MIT License 6 votes vote down vote up
/** Run a command and return the stdout, or if there was an error, throw. */
async function execAndThrowErrors(cmd: string, cwd?: string): Promise<void> {
  // tslint:disable-next-line:promise-must-complete
  return new Promise<void>((resolve, reject) => {
    exec(cmd, { encoding: "utf8", cwd }, (err, _stdout, stderr) => {
      if (stderr) {
        console.error(stderr);
      }

      if (err) {
        reject(err);
      } else {
        resolve();
      }
    });
  });
}
Example #26
Source File: storage.ts    From bedrock-cli with MIT License 6 votes vote down vote up
createResourceGroupIfNotExists = async (
  name: string,
  location: string
): Promise<void> => {
  if (!hasValue(name) || !hasValue(location)) {
    throw buildError(
      errorStatusCode.AZURE_RESOURCE_GROUP_ERR,
      "resource-group-create-err-missing-vals"
    );
  }

  const message = `Azure resource group ${name} in ${location} location`;
  try {
    logger.info(
      `Checking weather resource group ${name} exists in ${location} location.`
    );
    const response = await promisify(exec)(`az group exists -n ${name}`);
    if (response.stdout === "true") {
      logger.info(`${message} already exists.`);
    } else {
      logger.info(`Creating ${message}`);
      await promisify(exec)(`az group create -n ${name} -l ${location}`);
      logger.info(`Created ${message}`);
    }
  } catch (err) {
    throw buildError(
      errorStatusCode.AZURE_RESOURCE_GROUP_ERR,
      "resource-group-create-err",
      err
    );
  }
}
Example #27
Source File: terminal.ts    From disco-cube-daemon with MIT License 6 votes vote down vote up
executeCommand = async (command: string, cwd: string) => {
  return new Promise<{ error: string; stdout: string; stderr: string }>((resolve) => {
    logger.debug(`executing command '${command}'`);
    exec(command, { cwd }, (error, stdout, stderr) => {
      logger.debug(`command finished`, { error, stdout, stderr });
      resolve({ error: error ? error + "" : "", stdout, stderr });
    });
  });
}
Example #28
Source File: youtube.fallback.ts    From Discord-SimpleMusicBot with GNU General Public License v3.0 6 votes vote down vote up
export function execAsync(command:string):Promise<string>{
  return new Promise((resolve, reject) => {
    try{
      exec(command, (error, stdout, stderr) => {
        if(error){
          reject(stderr);
        }else{
          resolve(stdout);
        }
      });
    }
    catch(e){
      Util.logger.log(e, "error");
      reject("Main library threw an error and fallback library also threw an error");
    }
  });
}
Example #29
Source File: extensions.local.ts    From relate with GNU General Public License v3.0 6 votes vote down vote up
private async installRelateExtension(
        extension: IExtensionInfo,
        extractedDistPath: string,
    ): Promise<IExtensionInfo> {
        const target = this.environment.getEntityRootPath(ENTITY_TYPES.EXTENSION, extension.name);

        if (!(await fse.pathExists(extractedDistPath))) {
            throw new AmbiguousTargetError(`Path to extension does not exist "${extractedDistPath}"`);
        }

        if (await fse.pathExists(target)) {
            throw new ExtensionExistsError(`${extension.name} is already installed`);
        }

        await fse.copy(extractedDistPath, target);

        if (extension.type === EXTENSION_TYPES.STATIC && !isValidUrl(extension.main)) {
            const staticTarget = path.join(this.environment.dirPaths.staticExtensionsData, extension.name);

            await fse.symlink(target, staticTarget, 'junction');
        }

        // @todo: need to look at our use of exec (and maybe child processes) in general
        // this does not account for all scenarios at the moment so needs more thought
        const execute = promisify(exec);

        if (extension.type !== EXTENSION_TYPES.STATIC) {
            await emitHookEvent(
                HOOK_EVENTS.RELATE_EXTENSION_DEPENDENCIES_INSTALL_START,
                `installing dependencies for ${extension.name}`,
            );
            const output = await execute('npm ci --production', {
                cwd: target,
            });
            await emitHookEvent(HOOK_EVENTS.RELATE_EXTENSION_DEPENDENCIES_INSTALL_STOP, output);
        }

        return extension;
    }