Bun

指南运行时

使用 Bun 运行 Shell 命令

Bun Shell 是内置于 Bun 的跨平台类 bash shell。

它提供了一种在 JavaScript 和 TypeScript 中运行 Shell 命令的简单方法。要开始使用,请从 bun 包导入 $ 函数,并使用它来运行 Shell 命令。

foo.ts
import { $ } from "bun";

await $`echo Hello, world!`; // => "Hello, world!"

$ 函数是一个带有标签的模板字面量,它运行命令并返回一个解析为命令输出的 Promise。

foo.ts
import { $ } from "bun";

const output = await $`ls -l`.text();
console.log(output);

要将输出的每一行作为数组获取,请使用 lines 方法。

foo.ts
import { $ } from "bun";

for await (const line of $`ls -l`.lines()) {
  console.log(line);
}

有关完整文档,请参阅 文档 > API > Shell