问题
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)
How do I get the actual home directory(/home/username
) in all cases ?
回答1:
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:
os module
const os = require("os");
const user_name = os.userInfo().username;
const user_dir = os.userInfo().homedir;
console.log(user_name, user_dir);
From the NodeJS docs:
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 module
(original answer) If for some reason the above does not work, you can explicitly use getpwnam
to look up the actual home directory from /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);
You will need to install the posix
module first:
npm install posix
来源:https://stackoverflow.com/questions/65778302/default-home-directory-for-snap-installer-using-electron-builder