执行shell命令
child_process.exec
/*!
* @Author: CPS
* @email: 373704015@qq.com
* @Date: 2022-11-07 16:17:29.562967
* @Last Modified by: CPS
* @Last Modified time: 2022-11-07 16:17:29.562967
* @Projectname
* @file_path "W:\CPS\MyProject\test"
* @Filename "shell.ts"
* @Description: 功能描述
*/
import { promisify } from "util";
import child_process from "child_process";
const exec = promisify(child_process.exec);
export interface RunShellOptions {
encoding: string;
windowsHide: boolean;
cwd?: string;
}
export interface ResBase {
success: boolean;
res: any;
}
/**
* @Description - 运行`shell/bash`等指令
*
* @param {string|string[]} commands - 列表或字符串形式,字符串最终会以空格转换为列表
* @param {RunShellOptions} options - `windowsHide`是否后台执行,`cwd`指定工作目录,`encoding`指定编码等
*
* @returns {ResBase} - success判断是否执行成功,res获取对应结果
* @example
* ```js
* import { shell } from "shell"
*
* const command = ["npm", "list", "-g", "@mucpsing/cli"];
* const latestVersion = await shell(command);
* console.log("latestVersion: ", latestVersion);
*```
*/
export async function shell(
commands: string | string[],
options: RunShellOptions = { encoding: "utf-8", windowsHide: true, cwd: undefined }
): Promise<ResBase> {
// 支持以列表形式输入命令
if (Array.isArray(commands)) commands = commands.join(" ");
//
try {
const { stdout, stderr } = await exec(commands, { ...options });
if (stdout) return { success: true, res: stdout.trim() };
if (stderr) return { success: false, res: stderr.toString().trim() };
} catch (e) {
return { success: false, res: e };
}
}
import { promisify } from "util";
import child_process from "child_process";
const exec = promisify(child_process.exec);
const Commands = ["npm", "-v"];
export const Shell = async (
commands,
options = { encoding: "utf-8", windowsHide: true }
) => {
commands = commands.join(" ");
try {
const { stdout, stderr } = await exec(commands, options);
if (stdout) {
const res = stdout.trim();
return { sucess: true, res };
}
if (stderr) {
const err = stderr.toString();
return { sucess: false, err };
}
} catch (e) {
return { success: false, err: e.toString() };
}
};
require("child_process").spawn
const util = require("util");
const spawn = require("child_process").spawn;
const readline = require("readline");
let runner = spawn(config.python, [config.script, options], {
encoding: "utf-8",
windowsHide: true,
shell: process.platform === "win32",
stdio: [
0, // 使用父进程的 stdin 用于子进程。
"ipc", // 把子进程的 stdout 通过管道传到父进程 。
"ipc", // 把子进程的 stderr 定向到一个文件。
],
});
runner.stdout.on("data", async (data) => {
console.log("stdout: " + data);
console.log("设置123123", typeof data);
});
runner.on("close", (code) => {
console.log("close");
});