接口: Shell
2022/10/22约 696 字大约 2 分钟
shell.Shell
Shell 类,通过createShell创建新实例。
继承关系
EventEmitter↳
Shell
Shell 接口继承自 EventEmitter,因此可以使用所有 EventEmitter 的方法,如 on(), once(), off(), removeListener() 等。
目录
方法
Events
方法
exec
▸ exec(cmd): Promise<ExecutionResult>
执行 shell 命令,并等待执行结果。
示例
"nodejs";
const { createShell } = require("shell");
async function main() {
const shell = createShell();
console.log(await shell.exec("touch test.txt"));
console.log(await shell.exec("ls -l test.txt"));
await shell.exit();
}
main();参数
| 名称 | 类型 | 描述 |
|---|---|---|
cmd | string | 要执行的命令 |
返回值
Promise<ExecutionResult>
执行结果的 Promise
exit
▸ exit(forcedly?): Promise<ExitResult>
退出 shell 进程。若 forcedly 为 true,则会直接杀死进程,此时返回值为字符串,表示杀死进程的 signal;如果 forcedly 为 false,则会使用exit命令退出 shell 进程,并返回退出码(exit code)。
参数
| 名称 | 类型 | 描述 |
|---|---|---|
forcedly? | boolean | 是否强制退出 |
返回值
Promise<ExitResult>
submit
▸ submit(input): void
往 shell 的标准输入中提交文本内容,若文本内容末尾未包含换行符,则会自动添加换行符。
参数
| 名称 | 类型 |
|---|---|
input | string |
返回值
void
Events
on
▸ on(event, listener): Shell
监听 Shell 的输出事件。Shell 接口继承自 EventEmitter,支持两种事件类型:"data" 和 "line"。
示例
"nodejs";
const { createShell } = require("shell");
const shell = createShell();
// 监听数据事件(每次有新数据时触发)
shell.on("data", (chunk, type) => {
console.log(`收到 ${type} 数据:`, chunk.toString());
});
// 监听行事件(每次有新的一行时触发)
shell.on("line", (line, type) => {
console.log(`收到 ${type} 行:`, line);
});
shell.exec("ls -la");事件类型
"data" 事件
当 shell 的标准输出或标准错误输出有新数据时触发。
示例
"nodejs";
const { createShell } = require("shell");
const shell = createShell();
shell.on("data", (chunk, type) => {
if (type === "stdout") {
console.log("标准输出:", chunk.toString());
} else if (type === "stderr") {
console.error("标准错误:", chunk.toString());
}
});
shell.exec("echo 'Hello' && echo 'Error' >&2");参数("data" 事件)
| 名称 | 类型 | 描述 |
|---|---|---|
event | "data" | 事件名称,固定为 "data" |
listener | (chunk: Buffer, type: StandardOutputType) => void | 监听器函数。当有新数据时被调用,chunk 是数据缓冲区,type 表示是标准输出("stdout")还是标准错误("stderr") |
返回值
返回 Shell 对象本身,支持链式调用。
"line" 事件
当 shell 的标准输出或标准错误输出有新的一行数据时触发。
示例
"nodejs";
const { createShell } = require("shell");
const shell = createShell();
shell.on("line", (line, type) => {
if (type === "stdout") {
console.log("输出行:", line);
} else if (type === "stderr") {
console.error("错误行:", line);
}
});
shell.exec("ls -1");参数("line" 事件)
| 名称 | 类型 | 描述 |
|---|---|---|
event | "line" | 事件名称,固定为 "line" |
listener | (line: string, type: StandardOutputType) => void | 监听器函数。当有新的一行数据时被调用,line 是行内容(不包含换行符),type 表示是标准输出("stdout")还是标准错误("stderr") |
返回值
返回 Shell 对象本身,支持链式调用。
