Bun

指南執行時間

使用 Bun 執行 Shell 指令

Bun Shell 是一個跨平台的 bash 類似 shell,內建於 Bun 中。

它提供一種簡單的方法,可以在 JavaScript 和 TypeScript 中執行 shell 指令。要開始使用,請從 bun 套件匯入 $ 函式,並使用它來執行 shell 指令。

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

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

$ 函式是一個標記範本字串,用於執行指令並傳回一個承諾,承諾會解析指令的輸出。

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 以取得完整的說明文件。