t-comm
Version:
专业、稳定、纯粹的工具库
59 lines (56 loc) • 2.04 kB
JavaScript
import _typeof from '@babel/runtime/helpers/typeof';
/* eslint-disable @typescript-eslint/no-require-imports */
/**
* nodejs 中调用 child_process.execSync 执行命令,
* 这个方法会对输出结果截断,只返回第一行内容
* @param {string} command 命令
* @param {string} root 执行命令的目录
* @param {string | object} stdio 结果输出,默认为 pipe
* @returns {string} 命令执行结果
*/
function execCommand(command, root, options) {
var _a, _b, _c;
if (!root) {
root = process.cwd();
}
var execSync = require('child_process').execSync;
var innerOptions = {};
if (typeof options === 'string') {
innerOptions = {
stdio: options
};
} else if (_typeof(options) === 'object') {
innerOptions = options;
}
var stdio = (_a = innerOptions === null || innerOptions === void 0 ? void 0 : innerOptions.stdio) !== null && _a !== void 0 ? _a : 'pipe';
var line = (_b = innerOptions === null || innerOptions === void 0 ? void 0 : innerOptions.line) !== null && _b !== void 0 ? _b : 0;
var res = execSync(command, {
cwd: root || process.cwd(),
encoding: 'utf-8',
stdio: stdio || 'pipe'
});
if (line > -1) {
return ((_c = res === null || res === void 0 ? void 0 : res.split('\n')[line]) === null || _c === void 0 ? void 0 : _c.trim()) || '';
}
return res;
}
/**
* nodejs中调用 child_process.execSync 执行命令
* @param {string} command 命令
* @param {string} root 执行命令的目录
* @param {string} stdio 结果输出,默认为 pipe
* @returns {string} 命令执行结果
*/
function execCommandAll(command, root, stdio) {
var _a, _b;
if (!root) {
root = process.cwd();
}
var execSync = require('child_process').execSync;
return ((_b = (_a = execSync(command, {
cwd: root || process.cwd(),
encoding: 'utf-8',
stdio: stdio || 'pipe'
})) === null || _a === void 0 ? void 0 : _a.split('\n')[0]) === null || _b === void 0 ? void 0 : _b.trim()) || '';
}
export { execCommand, execCommandAll };