t-comm
Version:
专业、稳定、纯粹的工具库
73 lines (72 loc) • 3.07 kB
TypeScript
/// <reference types="node" />
import { type StdioOptions } from 'child_process';
/**
* 在 Node.js 中调用 child_process.execSync 执行命令
* 该方法会对输出结果进行处理,默认只返回指定行的内容(默认第一行)
* @param command - 要执行的命令字符串
* @param root - 执行命令的工作目录,默认为当前工作目录
* @param options - 配置选项,可以是字符串(stdio)或对象
* @param options.stdio - 标准输入输出配置,默认为 'pipe'
* @param options.line - 返回结果的行号,默认为 0(第一行),设置为 -1 返回全部内容
* @param options.throwError - 是否在命令执行失败时抛出错误,默认为 false
* @returns 命令执行结果字符串
* @example
* ```ts
* // 获取 git 分支名(第一行)
* const branch = execCommand('git branch', '/path/to/repo');
*
* // 获取完整输出
* const output = execCommand('ls -la', './', { line: -1 });
*
* // 自定义 stdio
* const result = execCommand('npm install', './', { stdio: 'inherit' });
* ```
*/
export declare function execCommand(command: string, root?: string, options?: string | {
stdio?: StdioOptions;
line?: number;
throwError?: boolean;
}): string;
/**
* execCommand 的偏函数应用版本,固定 throwError 为 true
* 当命令执行失败时会直接抛出错误,而非静默返回空字符串
* @param command - 要执行的命令字符串
* @param root - 执行命令的工作目录,默认为当前工作目录
* @param options - 配置选项,可以是字符串(stdio)或对象(不含 throwError,因为已固定为 true)
* @param options.stdio - 标准输入输出配置,默认为 'pipe'
* @param options.line - 返回结果的行号,默认为 0(第一行),设置为 -1 返回全部内容
* @returns 命令执行结果字符串
* @example
* ```ts
* // 执行失败时会抛出错误
* const branch = execCommandStrict('git branch', '/path/to/repo');
*
* // 配合 try-catch 使用
* try {
* const result = execCommandStrict('some-command');
* } catch (err) {
* console.error('命令执行失败:', err);
* }
* ```
*/
export declare function execCommandStrict(command: string, root?: string, options?: string | {
stdio?: StdioOptions;
line?: number;
}): string;
/**
* 在 Node.js 中调用 child_process.execSync 执行命令并返回第一行结果
* 该方法是 execCommand 的简化版本,始终返回输出的第一行
* @param command - 要执行的命令字符串
* @param root - 执行命令的工作目录,默认为当前工作目录
* @param stdio - 标准输入输出配置,默认为 'pipe'
* @returns 命令执行结果的第一行(去除首尾空格)
* @example
* ```ts
* // 获取当前 git 分支
* const branch = execCommandAll('git rev-parse --abbrev-ref HEAD');
*
* // 获取 Node 版本
* const nodeVersion = execCommandAll('node --version');
* ```
*/
export declare function execCommandAll(command: string, root?: string, stdio?: StdioOptions): string;