# 存取本地文件

我们可以很轻松地使用原生的 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-cn/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-cn/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.
