7、文件系统相关api以及基础的文件操作

章节目标

  • 学习和了解electron中,文件系统相关的api
  • 学习和了解,文件的基础操作
  • 通过主进程封装受控的原生能力,并在渲染端以安全 API 使用

electron文件系统介绍

electron的文件系统,是我们业务开发中,最常用的一个模块,当然它的api的使用,也是更复杂一些,使用的场景也会更加的丰富。

1、文件对话框 - dialog

dialog模块,封装了一套系统级别的对话框能力。
我们可以使用系统提供的dioalog,打开一个文件,或者保存一个文件。

// 文件对话框
ipcMain.handle("dialog:open-file", async () => {
	// showOpenDialog,打开一个对话框,如果properties,设置为:"openFile" 的时候,表示打开文件。
  const { canceled, filePaths } = await dialog.showOpenDialog({
    properties: ["openFile"],
  });
  // canceled为true,表示用户点击了取消。
  if (canceled || filePaths.length === 0) return null;
	// filePaths[0],表示打开的文件的,文件路径。
  return filePaths[0];
});

ipcMain.handle("dialog:save-file", async () => {
	// 保存文件的对话框。(canceled,表示是否用户点击了取消;filePath,表示文件保存的路径)
  const { canceled, filePath } = await dialog.showSaveDialog({
    defaultPath: "untitled.txt",
  });
  return canceled ? null : filePath;
});

2、文本文件操作

如果说,dialog提供了文件路径的选取和保存,那么真实对文件进行读和写的操作,就是要靠node的fs模块。

ipcMain.handle("fs:read-text", async (_e, filePath: string) => {
  try {
  	// fs.readFile进行文件内容读取。
    const content = await fs.readFile(filePath, "utf8");
    // 读取成功后,把读取的内容返回。
    return { success: true, content };
  } catch (error) {
    return { success: false, error: error.message };
  }
});

ipcMain.handle(
  "fs:write-text",
  async (_e, filePath: string, content: string) => {
    try {
      // 文件的写入操作,filePath是文件路径,content是写入的具体内容。
      await fs.writeFile(filePath, content, "utf8");
      // 写入成功后,返回成功标识
      return { success: true };
    } catch (error) {
      return { success: false, error: error.message };
    }
  }
);

3、获取系统目录路径

app.getPath(name),就是系统提供的获取特定目录的api。

  • home 用户的 home 文件夹(主目录)
  • appData 每个用户的应用程序数据目录
  • userData 储存你应用程序配置文件的文件夹
  • desktop 当前用户的桌面文件夹
  • documents 用户文档目录的路径
  • downloads 用户下载目录的路径

这些都是常用的一些文件目录,在特定的场景下会使用到。

使用场景:配置文件的某些场景。

以下是一个配置文件管理的一段核心代码

// 配置文件管理
ipcMain.handle("config:load", async () => {
	// 这里使用到了,app.getPath("userData") 这个api,通过该api,得到我们的配置文件的路径。
  const configPath = path.join(app.getPath("userData"), "config.json");
  try {
  	// 从配置文件中读取数据
    const data = await fs.readFile(configPath, "utf8");
    return { success: true, config: JSON.parse(data) };
  } catch (error) {
    // 配置文件不存在时返回默认配置
    return { success: true, config: { theme: "light", language: "zh-CN" } };
  }
});

ipcMain.handle("config:save", async (_e, config: any) => {
	// 配置文件的路径。(使用到了app.getPath("userData"))
  const configPath = path.join(app.getPath("userData"), "config.json");
  try {
  	// 向配置文件中写入内容
    await fs.writeFile(configPath, JSON.stringify(config, null, 2));
    return { success: true };
  } catch (error) {
    return { success: false, error: error.message };
  }
});

4、路径处理 (path)

  • 使用 path 模块处理跨平台路径
  • 常用方法:join(), resolve(), dirname(), basename(), extname()
  • 避免硬编码路径分隔符
import path from "node:path";

// 正确的路径处理
const userDataPath = path.join(app.getPath("userData"), "config.json");
const relativePath = path.resolve("./assets", "icon.png");

文件操作类型

在node进程中操作文件,有同步操作和异步操作两种方式,一般我们为了更好的性能体验,对于文件操作推荐使用异步的方式。

  1. 同步操作:阻塞主线程,简单但性能差
  2. 异步回调:传统 Node.js 风格
  3. Promise 版本:推荐使用,支持 async/await
// 推荐:Promise 版本
const content = await fs.readFile("file.txt", "utf8");
await fs.writeFile("output.txt", content);

// 避免:同步版本(阻塞)
const content = fs.readFileSync("file.txt", "utf8");

说明

文件操作相关知识,是electron应用开发的一个重点部分,本章节仅仅介绍了一些基本的api的使用以及有限的一些场景。
下个章节,我们继续以使用场景的方式切入,帮助大家了解electron的文件操作。
关注作者,我们一同学习和进步。

关于本专栏

本专栏的所有内容和代码,github地址:https://github.com/techLaoLi/electron-tutorial
关于作者,前大厂技术专家,现大前端技术负责人,公众号:老李说技术。 欢迎大家的关注。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老李说技术

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值