child_process#SpawnOptions TypeScript Examples
The following examples show how to use
child_process#SpawnOptions.
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: block-runner.ts From edge-impulse-cli with Apache License 2.0 | 6 votes |
async runAndWaitForNgrok(opts: {
command: string;
args: string[];
}, forwardStdio: boolean) {
return new Promise<void>((resolve, reject) => {
let spawnOpts: SpawnOptions = { };
if (forwardStdio) {
spawnOpts.stdio = 'inherit';
}
const p = spawn(opts.command, opts.args, spawnOpts);
if (!forwardStdio) {
p.stdout.on("data", (data: Buffer) => {
process.stdout.write(data);
});
p.stderr.on("data", (data: Buffer) => {
process.stderr.write(data);
});
}
p.on("error", (err) => {
process.stderr.write(err.toString());
});
p.on("exit", (code, signal) => {
if (typeof code === "number" && code !== 0) {
reject("Command exited with code " + code);
} else if (signal) {
reject("Terminated with signal " + signal);
} else {
resolve();
}
});
});
}
Example #2
Source File: launch.ts From TidGi-Desktop with Mozilla Public License 2.0 | 6 votes |
/**
* Open a given file or folder in the desired external editor.
*
* @param fullPath A folder or file path to pass as an argument when launching the editor.
* @param editor The external editor to launch.
*/
export async function launchExternalEditor(fullPath: string, editor: FoundEditor): Promise<void> {
const editorPath = editor.path;
const exists = await pathExists(editorPath);
if (!exists) {
const label = process.platform === 'darwin' ? 'Preferences' : 'Options';
throw new ExternalEditorError(
`Could not find executable for '${editor.editor}' at path '${editor.path}'. Please open ${label} and select an available editor.`,
{ openPreferences: true },
);
}
const options: SpawnOptions = {
// Make sure the editor processes are detached from the Desktop app.
// Otherwise, some editors (like Notepad++) will be killed when the
// Desktop app is closed.
detached: true,
};
if (editor.usesShell) {
spawn(`"${editorPath}"`, [`"${fullPath}"`], { ...options, shell: true });
} else if (process.platform === 'darwin') {
// In macOS we can use `open`, which will open the right executable file
// for us, we only need the path to the editor .app folder.
spawn('open', ['-a', editorPath, fullPath], options);
} else {
spawn(editorPath, [fullPath], options);
}
}
Example #3
Source File: spawn.ts From gitmars with GNU General Public License v3.0 | 6 votes |
/**
* 异步执行脚本
*
* @param client - 执行脚本的宿主,名称
* @param argv - 参数
* @param options - 透传配置
* @returns result - 返回执行状态
*/
export function spawn(
client: string,
argv: string[],
options: SpawnOptions = {}
): Partial<SpawnSyncReturns<string>> {
let len = argv.length
while (len--) {
!argv[len] && argv.splice(len, 1)
}
const program = crossSpawn.sync(client, argv, {
// stdio: 'inherit',
shell: process.platform === 'win32',
...options
})
debug(client, argv)
return {
pid: program.pid,
stdout: program.stdout
? program.stdout.toString().replace(/\s+$/, '')
: '',
stderr: program.stderr ? program.stderr.toString() : '',
status: program.status,
signal: program.signal,
error: program.error
}
}
Example #4
Source File: getGitStatus.ts From gitmars with GNU General Public License v3.0 | 6 votes |
/**
* 获取分支状态
*
* @param config - spawn配置
* @returns gitStatus - git状态
*/
function getGitStatus(config: SpawnOptions = {}): GitStatusInfoType {
const { stdout } = spawnSync('git', ['status', '-s', '--no-column'], config)
const list = stdout ? stdout.replace(/\n(\s+)/g, '\n').split('\n') : []
const sum: GitStatusInfoType = {
A: [],
D: [],
M: [],
UU: [],
'??': []
}
if (list.length === 0) return sum
list.forEach((str: string) => {
const arr: string[] = str.trim().replace(/\s+/g, ' ').split(' ')
const type = arr.splice(0, 1)[0] as keyof GitStatusInfoType
if (!sum[type]) sum[type] = []
sum[type].push(arr.join(' '))
})
debug('getGitStatus', sum)
return sum
}
Example #5
Source File: test-mount.ts From micropython-ctl with MIT License | 6 votes |
async start(verbose = false) {
const spawnOpts: SpawnOptions = {
stdio: verbose ? 'inherit' : undefined
}
this.allowedToExit = false
this.proc = spawn('yarn', ['mctl', 'mount'], spawnOpts)
this.proc.on('exit', () => {
if (!this.allowedToExit) {
console.error('mctl mount exited unexpectedly!')
process.exit(1)
}
})
}
Example #6
Source File: diskUsageUtil.ts From flood with GNU General Public License v3.0 | 6 votes |
spawnAsync = (cmd: string, args: string[], options: SpawnOptions, maxBuffer: number): Promise<string> =>
new Promise((resolve, reject) => {
const child = spawn(cmd, args, options);
let stdout = '';
let stderr = '';
child.once('error', (err) => {
reject(err);
});
child.stdout?.on('data', (chunk) => {
stdout += chunk.toString('utf-8');
if (stdout.length > maxBuffer) {
child.kill(9);
}
});
child.stderr?.on('data', (chunk) => {
stderr += chunk.toString('utf-8');
if (stderr.length > maxBuffer) {
child.kill(9);
}
});
child.on('close', (code) => {
if (code == 0) {
resolve(stdout);
} else {
reject(new Error(stderr));
}
});
})
Example #7
Source File: abstract.runner.ts From eslint-config-kit with MIT License | 6 votes |
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 #8
Source File: block-runner.ts From edge-impulse-cli with Apache License 2.0 | 6 votes |
async runAndWaitForCompletion(opts: {
command: string;
args: string[];
}, forwardStdio: boolean) {
return new Promise<void>((resolve, reject) => {
let spawnOpts: SpawnOptions = { };
if (forwardStdio) {
spawnOpts.stdio = 'inherit';
}
const p = spawn(opts.command, opts.args, spawnOpts);
if (!forwardStdio) {
p.stdout.on("data", (data: Buffer) => {
process.stdout.write(data);
});
p.stderr.on("data", (data: Buffer) => {
process.stderr.write(data);
});
}
p.on("error", (err) => {
process.stderr.write(err.toString());
});
p.on("exit", (code, signal) => {
if (typeof code === "number" && code !== 0) {
reject("Command exited with code " + code);
} else if (signal) {
reject("Terminated with signal " + signal);
} else {
resolve();
}
});
});
}
Example #9
Source File: process.ts From cli with Apache License 2.0 | 6 votes |
export async function spawnProcessOutput(
command: string,
args: string[],
options: SpawnOptions = {}
): Promise<SpawnProcessOutput> {
return new Promise((resolve) => {
const output: SpawnProcessOutput = {
stdout: '',
stderr: '',
};
const child = spawn(command, args, options);
child.stdout?.on('data', (d) => {
output.stdout += d;
});
child.stderr?.on('data', (d) => {
output.stderr += d;
});
const closeListener = (code: number | null) => {
output.exitCode = Number.isInteger(code) ? String(code) : undefined;
resolve(output);
};
child.on('close', closeListener);
child.on('error', (e) => {
output.stderr += e.message;
if (isErrnoException(e) && e.code) {
child.off('close', closeListener);
output.exitCode = e.code;
resolve(output);
}
});
});
}
Example #10
Source File: process.ts From cli with Apache License 2.0 | 6 votes |
/**
*
* @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);
}
});
});
}
Example #11
Source File: helpers.ts From backstage with Apache License 2.0 | 6 votes |
export async function runPlain(cmd: string[], options?: SpawnOptions) {
try {
const { stdout } = await execFile(cmd[0], cmd.slice(1), {
...options,
shell: true,
});
return stdout.trim();
} catch (error) {
assertError(error);
if (error.stdout) {
process.stdout.write(error.stdout as Buffer);
}
if (error.stderr) {
process.stderr.write(error.stderr as Buffer);
}
throw error;
}
}
Example #12
Source File: helpers.ts From backstage with Apache License 2.0 | 6 votes |
export function spawnPiped(cmd: string[], options?: SpawnOptions) {
function pipeWithPrefix(stream: NodeJS.WriteStream, prefix = '') {
return (data: Buffer) => {
const prefixedMsg = data
.toString('utf8')
.trimRight()
.replace(/^/gm, prefix);
stream.write(`${prefixedMsg}\n`, 'utf8');
};
}
const child = spawn(cmd[0], cmd.slice(1), {
stdio: 'pipe',
shell: true,
...options,
});
child.on('error', exitWithError);
const logPrefix = cmd.map(s => s.replace(/.+\//, '')).join(' ');
child.stdout?.on(
'data',
pipeWithPrefix(process.stdout, `[${logPrefix}].out: `),
);
child.stderr?.on(
'data',
pipeWithPrefix(process.stderr, `[${logPrefix}].err: `),
);
return child;
}
Example #13
Source File: Command.ts From vscode-dotnet-adapter with MIT License | 5 votes |
constructor(command: string, args: ReadonlyArray<string>, { env, ...options }: SpawnOptions) {
this.childProcess = spawn(command, args, { ...options, env: { ...process.env, ...env }});
this.exitCode = new Promise((resolve, reject) => {
this.childProcess.on('close', resolve);
this.childProcess.on('error', reject);
this.exitCodeRelease = resolve;
});
}
Example #14
Source File: spawn.ts From mysterium-vpn-desktop with MIT License | 5 votes |
spawnProcess = (
command: string,
args: ReadonlyArray<string>,
options: SpawnOptions = {},
): ChildProcess => {
log.info("Spawning a child process: ", command, ...args.map((a) => (a.indexOf(" ") != -1 ? `'${a}'` : a)))
return spawn(command, args, options)
}
Example #15
Source File: gulpfile.ts From SpaceEye with MIT License | 5 votes |
prodSpawnOptions: SpawnOptions = {
...defaultSpawnOptions,
env: {
...defaultSpawnOptions.env,
NODE_ENV: 'production'
}
}
Example #16
Source File: gulpfile.ts From SpaceEye with MIT License | 5 votes |
defaultSpawnOptions: SpawnOptions = {
env: {
PATH: EXTENDED_PATH
},
stdio: 'inherit',
shell: true
}
Example #17
Source File: processes.ts From dayz-server-manager with MIT License | 4 votes |
public async spawnForOutput(
cmd: string,
args?: string[],
opts?: {
verbose?: boolean;
ignoreCodes?: number[];
spawnOpts?: SpawnOptions | any;
dontThrow?: boolean;
stdOutHandler?: (data: string) => any;
stdErrHandler?: (data: string) => any;
},
): Promise<SpawnOutput> {
return new Promise((r, e) => {
const startTS = new Date().valueOf();
try {
const spawnedProcess = spawn(
cmd,
args,
opts?.spawnOpts,
);
let stdout = '';
if (spawnedProcess.stdout) {
spawnedProcess.stdout.on('data', (data) => {
if (opts?.verbose) {
this.log.log(LogLevel.DEBUG, `SPAWN OUT: ${data}`);
}
if (opts?.stdOutHandler) {
opts?.stdOutHandler(data);
}
stdout += data;
});
}
let stderr = '';
if (spawnedProcess.stderr) {
spawnedProcess.stderr.on('data', (data) => {
if (opts?.verbose) {
this.log.log(LogLevel.ERROR, `SPAWN ERR: ${data}`);
}
if (opts?.stdErrHandler) {
opts?.stdErrHandler(data);
}
stderr += data;
});
}
spawnedProcess.on('error', (error) => {
this.log.log(LogLevel.ERROR, error?.message ?? 'Spawned processes threw an error', error);
});
spawnedProcess.on('close', (code) => {
if (!spawnedProcess.stdout || !spawnedProcess.stderr) {
console.log('\n');
}
if (opts?.verbose) {
this.log.log(LogLevel.DEBUG, `Spawned process exited with code ${code}`);
this.log.log(LogLevel.DEBUG, `Duration: ${new Date().valueOf() - startTS}`);
}
if (!code || opts?.ignoreCodes?.includes(code) || opts?.dontThrow) {
r({ status: code ?? 0, stdout, stderr });
} else {
// eslint-disable-next-line prefer-promise-reject-errors
e({
status: code,
stdout,
stderr,
});
}
});
} catch (error) {
if (opts?.dontThrow) {
r({ status: 1, stdout: '', stderr: error?.message ?? '' });
} else {
// eslint-disable-next-line prefer-promise-reject-errors
e({ status: 1, stdout: '', stderr: error?.message ?? '' });
}
}
});
}