# 存取本機檔案

我們可以很輕鬆地使用原生的 Node.js API 來完成存取本機檔案的功能。這讓我們在插件系統中完成這樣的任務變得更加容易。

***

## 使用 `fs` 模組存取本機檔案 <a href="#iamlo" id="iamlo"></a>

利用 Node.js 的 `fs`的一系列方法來完成本機檔案存取，對本機檔案系統進行操作。例如，可以使用 `fs.readFile()` 方法來讀取檔案內容，使用 `fs.writeFile()` 方法來寫入檔案。這裏是一個範例：

```javascript
const fs = require('fs');

// 讀取檔案
fs.readFile('/path/to/file', (err, data) => {
  if (err) throw err;

  console.log(data);
});

// 寫入檔案
fs.writeFile('/path/to/file', 'hello world', (err) => {
  if (err) throw err;

  console.log('done');
});
```

這些方法都是非同步的，所以它們不會阻塞 UI，從而可以保證應用的高效能。另外，`fs` 模組還提供了一些其他有用的方法，例如可以用 `fs.stat()` 方法來取得檔案的大小、新增時間等資訊，也可以用 `fs.rename()` 方法來重新命名檔案。透過使用 `fs` 模組，我們可以很方便地存取本機檔案。

{% hint style="success" %}
**🦄 最佳實踐：** 儘可能不要使用 Node.js 裏面的 sync 方法，這些方法會導致 UI 執行緒阻塞，從而導致使用者介面卡頓，使用者體驗極差。此外，使用非同步方法能夠提高程式的執行效率，因為它不會阻塞程式的執行，可以同時處理多個任務。
{% endhint %}

***

## 使用原生對話框取得檔案路徑 <a href="#nyq1o" id="nyq1o"></a>

Eagle Plugin API 提供了一個 `dialog` 模組，可以用來新增原生系統對話框，進行檔案儲存及選取。這裏有耶些範例：

**範例一：彈出檔案選擇對話框**

```javascript
let result = await eagle.dialog.showOpenDialog({
    properties: ['openFile', 'openDirectory']
});
```

**範例二：彈出儲存對話框**

```javascript
let result = await eagle.dialog.showSaveDialog({
    properties: ['openDirectory']
});
```

如果你需要更詳細的介紹，可以參考 [dialog 模組](/plugin-api/zh-tw/api/dialog.md)。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://developer.eagle.cool/plugin-api/zh-tw/tutorial/access-local-files.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
