How to get the original path of a portable Electron app?

℡╲_俬逩灬. 提交于 2019-12-18 11:57:54

问题


I have an Portable Electron App (packed with: electron-builder + asar, portable build) on Windows. I try to get the application path but it returns a path within the user\temp folder rather than the actual '.exe' file

Is there any way to get the original app.exe path?

I've tried the following:

  • app.getAppPath()
  • __dirname
  • require.main.filename
  • app-root-path
  • and a few node modules

The path I'm getting from my tests:

C:\Users\xxx\AppData\Local\Temp\xxxxxx.tmp\app

the actual .exe Path (where the app launched from, and what i need):

C:\Users\XXX\Documents\test\dist

I'm just starting with Electron.


回答1:


I found a solution: Use the Environment Variable (created by Electron-Builder)

process.env.PORTABLE_EXECUTABLE_DIR

to show the real Path of the App.exe. Works only packed with Electron-Builder




回答2:


From the main process:

// If not already defined...
const { app } = require ('electron');
const path = require ('path');

let execPath;

execPath = path.dirname (app.getPath ('exe'));
// or
execPath = path.dirname (process.execPath);

From a renderer process:

// If not already defined...
const { remote } = require ('electron');
const path = require ('path');

let execPath;

execPath = path.dirname (remote.app.getPath ('exe'));
// or
execPath = path.dirname (remote.process.execPath);



回答3:


None of the above answers worked for me on Windows 10.

process.env.PORTABLE_EXECUTABLE_DIR returns the Temp directory path.

I got it to work using:

process.env.INIT_CWD



回答4:


process.env.PORTABLE_EXECUTABLE_FILE

will give you the full path to the file.




回答5:


As none of the methods above worked and I don't want to use an external lib for this, i tried following:

        if (!fs.existsSync("../images")) {
            fs.mkdirSync("./../images");            
        }
        return path.resolve("./../images/") + "/";

You can use any directory that should exist at the top level or anywhere else. In my case I know that one level higher in the directory there must be a directory called "images".

This solution worked in my case for DEV build and prod (packaged).

Are there any drawbacks when using this approach?



来源:https://stackoverflow.com/questions/46307797/how-to-get-the-original-path-of-a-portable-electron-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!