使用电子生成器的快照安装程序的默认主目录 [英] Default home directory for snap installer using electron-builder

查看:52
本文介绍了使用电子生成器的快照安装程序的默认主目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在构建电子应用程序,并使用电子构建器构建 .deb .snap 之类的安装程序.在应用程序内部,出于某种原因,我需要访问用户主目录,并且我正在使用 process.env.HOME ||process.env.USERPROFILE 来获取主目录( app.getPath('home')也会返回相同目录).这在其他情况下也可以正常使用,但是当应用程序安装了 .snap 而不是实际的home(/home/username )目录时,它将返回〜/snap/< app_name>/3/作为主目录.( 3 是快照修订号)

I'm currently building a electron app an building the installer like .deb and .snap with electron-builder. Inside the app I need the access the user home directory for some reason and I'm using process.env.HOME || process.env.USERPROFILE to get the home directory (also app.getPath('home') returns the same). This works properly for other cases but when the app installed with .snap, instead of the actual home(/home/username) directory this returns ~/snap/<app_name>/3/ as home directory. (3 is the snap revision number)

在所有情况下如何获取实际的主目录(/home/username )?

How do I get the actual home directory(/home/username) in all cases ?

推荐答案

请注意,〜/不是有效路径;它被外壳扩展为 $ HOME .在大多数情况下,您要查找的实际路径为/home/username .一个简单的解决方案是简单地假设它是主目录.

Note that ~/ is not a valid path; it is expanded to $HOME by the shell. The actual path you're looking for will be /home/username in most cases. A simplistic solution would be to simply assume that to be the home dir.

为防止主文件夹不在此位置,我们应该询问操作系统:

To safeguard against situations where the home folder is not at this location, we should ask the operating system:

const os = require("os");

const user_name = os.userInfo().username;
const user_dir = os.userInfo().homedir;

console.log(user_name, user_dir);

NodeJS文档:

由os.userInfo()返回的homedir的值由操作系统提供.这与os.homedir()的结果不同,它在回落到操作系统响应之前先查询环境变量的主目录.

The value of homedir returned by os.userInfo() is provided by the operating system. This differs from the result of os.homedir(), which queries environment variables for the home directory before falling back to the operating system response.

posix模块

(原始答案)如果由于某种原因上述方法不起作用,则可以显式使用 getpwnam /etc/passwd 查找实际的主目录:

const posix = require("posix");
const os = require("os");

const user_name = os.userInfo().username;
const user_dir = posix.getpwnam(user_name).dir;

console.log(user_name, user_dir);

您将需要先安装 posix 模块:

npm install posix

这篇关于使用电子生成器的快照安装程序的默认主目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆