詳解如何在Electron中存取本地文件
最近在使用 Electron 做一個(gè)手寫字體生成圖片的工具。 不可避免的,遇到了通過Electron 往本地存文件的問題。
在Electron 中,存取本地文件,有很多種辦法。本文介紹最常用的一種辦法。 通過 Electron 框架提供的能力,和 Node.js 的 fs 文件管理模塊實(shí)現(xiàn)本地文件的存取。
使用 app.getPath 和 fs 模塊存儲(chǔ)文件
首先,我們可以通過 app.getPath 來獲取當(dāng)前用戶的 data 存放目錄。
app.getPath(’userData’) 返回一個(gè)字符串,該字符串表示應(yīng)用程序的用戶數(shù)據(jù)目錄的路徑。這個(gè)目錄通常是用來存儲(chǔ)用戶相關(guān)的數(shù)據(jù),例如配置文件、緩存等。具體路徑會(huì)根據(jù)操作系統(tǒng)而變化。
- windows 系統(tǒng)中, 會(huì)返回類似(
C:\Users\<username>\AppData\Roaming\<YourAppName>)這樣的結(jié)果。 - Mac 系統(tǒng)中,會(huì)返回(
/Users/<username>/Library/Application Support/<YourAppName>) 這種結(jié)果。 - linux 系統(tǒng)中 則會(huì)返回 (
/home/<username>/.config/<YourAppName>) 這種結(jié)果。
我們通過 node.js 的path 模塊, 使用 path.join(app.getPath('userData'), 'myFile.txt') 就能得到一個(gè)完整的文件路徑。 接著使用 fs 模塊的 來寫入內(nèi)容即可。
示例代碼如下:
const {
app
} = require('electron');
const fs = require('fs');
const path = require('path');
const filePath = path.join(app.getPath('userData'),'/myfile.txt'); // Example file path
try {
fs.writeFileSync(filePath, 'hello world', 'utf-8');
} catch (e) {
console.error('Failed to save the file!');
}這種做法,有一個(gè)問題。那就是,用戶不能在保存的時(shí)候,主動(dòng)選擇文件存放目錄。
使用 Dialog API 和 fs 模塊配合
Electron 提供了一個(gè) Dialog API 來處理文件對(duì)話框。您可以專門調(diào)用一個(gè)保存對(duì)話框,讓用戶選擇保存文件的位置。
下面是一個(gè)簡(jiǎn)單的,示例代碼:
const {
dialog
} = require('electron').remote;
const fs = require('fs');
const options = {
title: 'Save file',
defaultPath: 'my_filename',
buttonLabel: 'Save',
filters: [{
name: 'txt',
extensions: ['txt']
},
{
name: 'All Files',
extensions: ['*']
},
],
};
dialog.showSaveDialog(null, options).then(({
filePath
}) => {
if (filePath) {
fs.writeFileSync(filePath, 'hello world', 'utf-8');
}
});需要注意的點(diǎn):
因?yàn)?fs 模塊 和 Dialog 只能在,主進(jìn)程中被調(diào)用。 但是我們的應(yīng)用程序交互邏輯是在渲染進(jìn)程,所以這段示例代碼,只是演示了,如何去調(diào)用 Dialog 并手動(dòng)選擇文件存儲(chǔ)位置。 并沒有實(shí)際應(yīng)用場(chǎng)景的參考意義。
實(shí)際應(yīng)用場(chǎng)景封裝 調(diào)整
對(duì)存取圖片的封裝想法跟之前的采集桌面思路基本一致(如果,沒看過可以翻一下以前的文章)。 我們利用 Electron 的 ipcmain 模塊在主進(jìn)程中注冊(cè)方法。 然后,在渲染進(jìn)程去調(diào)用。 整理實(shí)現(xiàn)流程大概如下圖所示。

實(shí)例代碼:
// 主進(jìn)程 -> main.js
// .... ohter code
// ... 在主進(jìn)程注冊(cè)我們封裝后的 SaveFile 方法
const { app, BrowserWindow, ipcMain, dialog} = require("electron");
const path = require("path");
const fs = require('fs');
/**
* @param options: { title: String, defaultPath: String, buttonLabel: String, filters: area}
* @param content: String
* @returns Promise
*/
ipcMain.handle('saveFile', async (event, content, options) => {
let path;
try {
const { filePath } = await dialog.showSaveDialog(null, options);
path = filePath;
} catch(e) {
return Promise.reject({error: e, success: false});
}
if(path) {
try {
fs.writeFileSync(path, content, 'utf-8');
return Promise.resolve({error: null, success: true});
} catch(e) {
return Promise.reject({error: e, success: false});
}
} else {
return Promise.reject({error: e, success: false, canceled: true});
}
});
// 其他代碼 ....// Vue 文件、
// 在我們,的Vue 業(yè)務(wù)中。直接通過 ipc 調(diào)用
<script setup>
import {reactive, ref, onMounted} from "vue";
const textContent = ref('hello world');
const { ipcRenderer } = require('electron');
const exportImg = async () => {
try {
// 注意-> 第一個(gè)參數(shù),為 主進(jìn)程注冊(cè)進(jìn)來的方法名稱。
// 其他參數(shù)為, 主進(jìn)程注冊(cè)的函數(shù)參數(shù)。
await ipcRenderer.invoke('saveFile', 'hello', {
title: '導(dǎo)出圖片',
buttonLabel: '導(dǎo)出',
defaultPath: 'text.txt',
filters: [{
name: 'All Files',
extensions: ['*']
}]
})
} catch(e) {
console.error('出錯(cuò)了!', e)
}
}
</script>
<template>
<a-config-provider :csp="{ nonce: 'YourNonceCode' }">
<a-button type="primary" @click="exportImg">導(dǎo)出</a-button>
</a-config-provider>
</template>總結(jié)
在Electron 中,向本地存儲(chǔ)和讀取文件(文本或者是圖片), 都離不開 node.js 的 fs 模塊, 這個(gè)是文件系統(tǒng)處理的核心模塊。
然后,我們搭配, path 模塊。 dialog 模塊,可以實(shí)現(xiàn),用戶主動(dòng)選擇存放位置。 或者 直接存到默認(rèn)軟件系統(tǒng)的 data 目錄中。
當(dāng)然,這些模塊都只能在主進(jìn)程中使用。 所以,我們不可避免的用到了, 之前的老朋友, ipc 進(jìn)程間通訊方式。
到此這篇關(guān)于詳解如何在Electron中存取本地文件的文章就介紹到這了,更多相關(guān)Electron存取本地文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue實(shí)現(xiàn)動(dòng)態(tài)監(jiān)測(cè)元素高度
這篇文章主要介紹了vue實(shí)現(xiàn)動(dòng)態(tài)監(jiān)測(cè)元素高度方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-10-10
vue2.0使用Sortable.js實(shí)現(xiàn)的拖拽功能示例
本篇文章主要介紹了vue2.0使用Sortable.js實(shí)現(xiàn)的拖拽功能示例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下。2017-02-02
vue+electron實(shí)現(xiàn)創(chuàng)建多窗口及窗口間的通信(實(shí)施方案)
這篇文章主要介紹了vue+electron實(shí)現(xiàn)創(chuàng)建多窗口及窗口間的通信,本文給大家分享實(shí)施方案結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-09-09
Vue.js計(jì)算屬性computed與watch(5)
這篇文章主要為大家詳細(xì)介紹了Vue.js計(jì)算屬性computed與watch,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-12-12

