欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解如何在Electron中存取本地文件

 更新時間:2023年11月30日 10:08:26   作者:Sean  
在Electron 中,存取本地文件,有很多種辦法,本文介紹最常用的一種辦法, 通過 Electron 框架提供的能力,和 Node.js 的 fs 文件管理模塊實(shí)現(xiàn)本地文件的存取,需要的小伙伴可以參考下

最近在使用 Electron 做一個手寫字體生成圖片的工具。 不可避免的,遇到了通過Electron 往本地存文件的問題。

在Electron 中,存取本地文件,有很多種辦法。本文介紹最常用的一種辦法。 通過 Electron 框架提供的能力,和 Node.js 的 fs 文件管理模塊實(shí)現(xiàn)本地文件的存取。

使用 app.getPath 和 fs 模塊存儲文件

首先,我們可以通過 app.getPath 來獲取當(dāng)前用戶的 data 存放目錄。

app.getPath(’userData’) 返回一個字符串,該字符串表示應(yīng)用程序的用戶數(shù)據(jù)目錄的路徑。這個目錄通常是用來存儲用戶相關(guān)的數(shù)據(jù),例如配置文件、緩存等。具體路徑會根據(jù)操作系統(tǒng)而變化。

  • windows 系統(tǒng)中, 會返回類似(C:\Users\<username>\AppData\Roaming\<YourAppName>)這樣的結(jié)果。
  • Mac 系統(tǒng)中,會返回(/Users/<username>/Library/Application Support/<YourAppName>) 這種結(jié)果。
  • linux 系統(tǒng)中 則會返回 (/home/<username>/.config/<YourAppName>) 這種結(jié)果。

我們通過 node.js 的path 模塊, 使用 path.join(app.getPath('userData'), 'myFile.txt') 就能得到一個完整的文件路徑。 接著使用 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!');
}

這種做法,有一個問題。那就是,用戶不能在保存的時候,主動選擇文件存放目錄。

使用 Dialog API 和 fs 模塊配合

Electron 提供了一個 Dialog API 來處理文件對話框。您可以專門調(diào)用一個保存對話框,讓用戶選擇保存文件的位置。

下面是一個簡單的,示例代碼:

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 并手動選擇文件存儲位置。 并沒有實(shí)際應(yīng)用場景的參考意義。

實(shí)際應(yīng)用場景封裝 調(diào)整

對存取圖片的封裝想法跟之前的采集桌面思路基本一致(如果,沒看過可以翻一下以前的文章)。 我們利用 Electron 的 ipcmain 模塊在主進(jìn)程中注冊方法。 然后,在渲染進(jìn)程去調(diào)用。 整理實(shí)現(xiàn)流程大概如下圖所示。

實(shí)例代碼:

// 主進(jìn)程 ->  main.js

// .... ohter code
// ... 在主進(jìn)程注冊我們封裝后的 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 {
            // 注意->  第一個參數(shù),為 主進(jìn)程注冊進(jìn)來的方法名稱。 
      // 其他參數(shù)為, 主進(jìn)程注冊的函數(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('出錯了!', 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 中,向本地存儲和讀取文件(文本或者是圖片), 都離不開 node.js 的 fs 模塊, 這個是文件系統(tǒng)處理的核心模塊。

然后,我們搭配, path 模塊。 dialog 模塊,可以實(shí)現(xiàn),用戶主動選擇存放位置。 或者 直接存到默認(rèn)軟件系統(tǒng)的 data 目錄中。

當(dāng)然,這些模塊都只能在主進(jìn)程中使用。 所以,我們不可避免的用到了, 之前的老朋友, ipc 進(jìn)程間通訊方式。

到此這篇關(guān)于詳解如何在Electron中存取本地文件的文章就介紹到這了,更多相關(guān)Electron存取本地文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論