Bun

指南讀取檔案

使用 Bun 監視目錄更改

Bun 實現 `node:fs` 模組,包括用於監聽檔案系統更改的 `fs.watch` 函式。

此程式碼塊監視當前目錄中檔案的更改。預設情況下,此操作是*淺層*的,這意味著子目錄中檔案的更改將不會被檢測到。

import { watch } from "fs";

const watcher = watch(import.meta.dir, (event, filename) => {
  console.log(`Detected ${event} in ${filename}`);
});

要監視子目錄中的更改,請將 `recursive: true` 選項傳遞給 `fs.watch`。

import { watch } from "fs";

const watcher = watch(
  import.meta.dir,
  { recursive: true },
  (event, filename) => {
    console.log(`Detected ${event} in ${filename}`);
  },
);

使用 `node:fs/promises` 模組,您可以使用 `for await...of` 而不是回撥函式來監聽更改。

import { watch } from "fs/promises";

const watcher = watch(import.meta.dir);
for await (const event of watcher) {
  console.log(`Detected ${event.eventType} in ${event.filename}`);
}

要停止監聽更改,請呼叫 `watcher.close()`。當程序收到 `SIGINT` 訊號時(例如使用者按下 Ctrl-C 時),通常會執行此操作。

import { watch } from "fs";

const watcher = watch(import.meta.dir, (event, filename) => {
  console.log(`Detected ${event} in ${filename}`);
});

process.on("SIGINT", () => {
  // close watcher when Ctrl-C is pressed
  console.log("Closing watcher...");
  watcher.close();

  process.exit(0);
});

有關在 Bun 中使用 `Uint8Array` 和其他二進位制資料格式的更多資訊,請參閱 API > 二進位制資料 > 型別化陣列