Home > other >  Vue3 Electron get user docs folder
Vue3 Electron get user docs folder

Time:03-04

How can i get the user docs folder path for an electron app running on the desktop. I've tried the following but get an error that app is undefined.

import fs from "fs";
const { app } = require("electron");

export function getFilepath() {
  const filepath = app.getPath("userData")   "/settings.json";
  return filepath;
}

This code lives in a helpers.js file that is being import through my electron_preload.js file.

I have no clue what or how to solve this.

import { contextBridge, ipcRenderer } from "electron";
const helpers= require("../src/helpers");

contextBridge.exposeInMainWorld("helpers", helpers);

CodePudding user response:

Since you're executing the code in your preload environment, it is being run in the renderer process of the corresponding BrowserWindow. However, app is limited to the main process' execution scope (source) which is why your code throws the error.

You will have to expose the path via IPC.

// Main process, app.js or whatever
const { ipcMain, app } = require ("electron");

ipcMain.handle ("get-user-data-path", (event, ...args) => {
    return app.getPath ("userData")   "/settings.json";
});
// In helpers.js
import fs from "fs";
const { ipcRenderer } = require("electron");

export async function getFilepath () {
    return await ipcRenderer.invoke ("get-user-data-path");
}

For a more in-depth explanation, see the official Electron IPC tutorial.

(As a side note: I/O to the filesystem should probably be done by the main process, not the renderer. Worth considering from a security point of view.)

  • Related