Electron读取静态文件夹文件

前提

项目是由electron-vite搭建的

主进程

在主进程读取public/sound-effects下的所有文件,然后拼接成一个数组使用

js 复制代码
import { ipcMain, app } from "electron"
import fs from "fs"
import path from "path"

ipcMain.handle('getAllSounds', () => {
    return getSoundsEffect()
})

const soundEffectsDir = path.join(app.getAppPath(), "public/sound-effects")

// 读取sound-effects文件夹中所有的json,合并成一个数组
const getSoundsEffect = () => {
    try {
        console.log("sounds address:", soundEffectsDir)
        const files = fs.readdirSync(soundEffectsDir)
        const jsonFiles = files.filter(file => path.extname(file) === '.json')
        const reduceData = jsonFiles.reduce((acc, file) => {
            const filePath = path.join(soundEffectsDir, file)
            const data = fs.readFileSync(filePath, 'utf-8')
            const jsonData = JSON.parse(data)
            acc.push(jsonData)
            return acc
        }, [] as any[])
        return reduceData
    } catch (error) {
        console.error('sounds address read error:', error)
        return []
    }
}

渲染进程

js 复制代码
    const getSoundsEffect = async () => {
        const result = await window.ipcRenderer?.invoke('getAllSounds')
        setSounds(result || [])
    }

注意

electron-builder.json中需要额外配置环境,打包后才能正确读取到路径

js 复制代码
  "files": [
    "dist",
    "dist-electron",
    "public"  // 新增 public
  ],