Node.js - Find home directory in platform agnostic way

99封情书 提交于 2019-11-26 11:53:38

问题


Process.platform returns \"win32\" for Windows. On Windows a user\'s home directory might be C:\\Users[USERNAME] or C:\\Documents and Settings[USERNAME] depending on which version of Windows is being used. On Unix this isn\'t an issue.


回答1:


As mentioned in a more recent answer, the preferred way is now simply:

const homedir = require('os').homedir();

[Original Answer]: Why not use the USERPROFILE environment variable on win32?

function getUserHome() {
  return process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'];
}



回答2:


os.homedir() was added by this PR and is part of the public 4.0.0 release of nodejs.


Example usage:

const os = require('os');

console.log(os.homedir());



回答3:


Well, it would be more accurate to rely on the feature and not a variable value. Especially as there are 2 possible variables for Windows.

function getUserHome() {
  return process.env.HOME || process.env.USERPROFILE;
}

EDIT: as mentioned in a more recent answer, https://stackoverflow.com/a/32556337/103396 is the right way to go (require('os').homedir()).




回答4:


Use osenv.home(). It's maintained by isaacs and I believe is used by npm itself.

https://github.com/isaacs/osenv




回答5:


getUserRootFolder() {
  return process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
}


来源:https://stackoverflow.com/questions/9080085/node-js-find-home-directory-in-platform-agnostic-way

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