外壳
命令执行和 shell 解析器 dax。 。 。 .
多数用户应联系 dax 它以这个包为基础,并增加了进度栏,伐木, request, (中文(简体) ), which,以及其他便利。 使用 @david/shell 直接当您想要的只是外壳层.
工作在德诺和Node.js.
安装
# npm
npm install @dsherret/shell
# jsr
deno add jsr:@david/shell
使用量
import $ from "@dsherret/shell";
// run a command (stdout inherits by default)
await $`echo 1 && echo 2`;
// capture output
const text = await $`echo hello`.text();
console.log(text); // "hello"
// interpolated args are escaped by default
const name = "some name with spaces";
await $`echo ${name}`;
// $.raw disables argument escaping
await $.raw`echo one two three`;
// $.rawArg opts a single value out of escaping
await $`echo ${$.rawArg("1 2 3")}`;
内插命令
将命令替换到其捕获的 stdout, 类似于 $(...) 在外壳中:
const name = $`echo world`;
await $`echo hello ${name}`; // hello world
await $`echo 'hello ${name}'`; // works inside quotes too
await $`cat < ${name}`; // or as an input redirect
内插命令在周边命令评价其参数时会懒散地运行,所以当短路离开时它就永远不会运行(例如插到 $`exit 1 && echo ${cmd}` 不运行). 它使用自己的配置执行(env,cwd等),但stdout被捕获并stderr默认为评价命令的stderr. 如果失败, 评估它的命令会以退出代码失败 .noThrow() 以容忍失败 一样 $(...),只有在没有其他东西先决定退出代码(ex. $`echo ${cmd} | cat` 带有 cat'状态,除非 .pipefail() 已设定).
喜欢 $(...),一个未被引用的替代单词将其输出分解成多个参数并扩展出 glob 字符——插入内引出(ex. $`echo "${cmd}"`)以一一辩.
在输入重定向位置, $`cat < ${cmd}` 将命令的原始 stdout 直接流到重定向( 没有抓取或分字) , 而引用 $`cat < "${cmd}"` 将其输出替换为要读取的文件路径。 流出命令的退出代码只在读取命令消耗其全部输出时——当读取命令提前停止时,它就会被杀死并被忽略,就像管子的左侧一样.
内插值或字面命令文本都不得包含 NUL 字符(\0)——它被保留为内部划界人,所以无论哪种情况都会导致 TypeError。 。 。 .
build$
build$ 创建一个 $ 约束于特定 CommandBuilder 和/或附有额外属性.
import { build$, CommandBuilder } from "@dsherret/shell";
const $ = build$({
commandBuilder: new CommandBuilder().env("MY_VAR", "123"),
extras: {
add(a: number, b: number) {
return a + b;
},
},
});
await $`echo $MY_VAR`; // uses the configured env
console.log($.add(1, 2)); // 3
打电话 $.build$(...) 生出一个孩子 $ 它继承了父命令构建器状态,并合并了顶上的任何新的额外内容.
自定义命令
注册一个执行内置命令的处理器 :
import { CommandBuilder } from "@dsherret/shell";
const result = await new CommandBuilder()
.registerCommand("greet", async (ctx) => {
await ctx.stdout.writeLine(`hello ${ctx.args[0] ?? "world"}`);
return { code: 0 };
})
.command("greet friend")
.stdout("piped");
console.log(result.stdout); // "hello friend\n"
见 mod.ts 完全公开的API: $编号 :build$, (中文(简体) ), CommandBuilder, (中文(简体) ), CommandChild, (中文(简体) ), CommandResult, (中文(简体) ), KillController编号 :KillSignal, (中文(简体) ), ProcessTracker, (中文(简体) ), escapeArg, (中文(简体) ), createExecutableCommand,文件帮助者(create, (中文(简体) ), open, (中文(简体) ), FsFile),以及命令处理器、管子和弹壳结果的类型.