【Electron】解决windows系统无法创建文件夹及写文件的问题

1,644 阅读3分钟

本文已参与「新人创作礼」活动, 一起开启掘金创作之路。

一、前言

本篇主要讲述如何解决ELectron应用在windows系统中,无法通过node读写本地文件的问题。在我们的日常开发过程中,有可能会遇到将图片或者文件写入到本地缓存起来的需求,本篇文章你就能用得上。

二、解决方案

这里我们讲述两个解决方案,各有优缺点。

1.将安装包默认为最高权限

简单来说就是我在打包的时候,将安装包的权限设置为最高权限,用户在安装完之后,默认的启动方式只能是以管理员身份运行,我们应用的图标右下角也会显示一个小盾牌的样子。

另外还得说明一下,本文使用的打包工具为electron-builder。实现方式如下

// 打包配置

electronBuilder: {
    win: {
        requestedExecutionLevel: 'highestAvailable',
    }
}

在打包配置中添加这项配置即可。点击查看文档

原文中的描述如下

requestedExecutionLevel = asInvoker “asInvoker” | “highestAvailable” | “requireAdministrator” | “undefined” - The security level at which the application requests to be executed. Cannot be specified per target, allowed only in the win.

注意:因为在windows系统中,如果以最高权限(即管理员权限)运行程序,则不可以将其他文件拖拽到此应用中,所以这样会造成拖拽功能(如拖拽上传文件)与创建文件功能互斥。

ps:这里我使用部分win7电脑没有此问题,但是win10必有此问题。(这里就没有再深究了。有兴趣的小伙伴可以研究研究)。

2.在特定目录下进行文件读写

electron主进程中的app模块有一个方法是getPath,咱们可以使用这个方法,获取我们可以操作的文件读写的路径。创建的文件夹和文件就放到这个目录下面即可。代码如下

import fs from 'fs' 
const path = require('path') 

const TEMPPATH = 'temp' // 生成的文件夹名称
const basePath = path.join(app.getPath('userData'), TEMPPATH) 
fs.mkdir(basePath, { recursive: true }, err => { 
    if (err) console.log(`mkdir path: ${basePath} err`) 
})

具体文档内容如下;点击查看文档详情

app.getPath(name)

  • name string - 您可以通过名称请求以下路径:

    • home 用户的 home 文件夹(主目录)

    • appData 每个用户的应用程序数据目录,默认情况下指向:

      • %APPDATA% Windows 中
      • $XDG_CONFIG_HOME or ~/.config Linux 中
      • ~/Library/Application Support macOS 中
    • userData The directory for storing your app's configuration files, which by default is the appData directory appended with your app's name. By convention files storing user data should be written to this directory, and it is not recommended to write large files here because some environments may backup this directory to cloud storage.

    • sessionData The directory for storing data generated by Session, such as localStorage, cookies, disk cache, downloaded dictionaries, network state, devtools files. By default this points to userData. Chromium may write very large disk cache here, so if your app does not rely on browser storage like localStorage or cookies to save user data, it is recommended to set this directory to other locations to avoid polluting the userData directory.

    • temp 临时文件夹

    • exe当前的可执行文件

    • module The libchromiumcontent 库

    • desktop 当前用户的桌面文件夹

    • documents 用户文档目录的路径

    • downloads 用户下载目录的路径

    • music 用户音乐目录的路径

    • pictures 用户图片目录的路径

    • videos 用户视频目录的路径

    • recent 用户最近文件的目录 (仅限 Windows)。

    • logs应用程序的日志文件夹

    • crashDumps 崩溃转储文件存储的目录。

返回 string - 与 name 关联的目录或文件的路径。 失败会抛出一个Error

如果 app.getPath('logs') 被调用前没有先调用 app.setAppLogsPath() ,将创建一个相当于调用 app.setAppLogsPath() 却没有 path 参数的默认日志目录。

通过这种方法,我们就解决了windows系统无法创建文件夹的问题了。并且这种方式并不会与windows的拖拽功能产生互斥的问题。

三、后记

这里咱们建议使用第二种方式,在userData中,存储用户数据的文件应写入此目录,不建议在此处写入大文件,因为某些环境可能会将此目录备份到云存储。

本篇完结! 撒花! 感谢观看! 希望能帮助到你!