Node.js - 以与平台无关的方式查找主目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9080085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:06:40  来源:igfitidea点击:

Node.js - Find home directory in platform agnostic way

node.jsfilesystemsplatform-independenthome-directoryplatform-agnostic

提问by Matthew

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.

Process.platform 为 Windows 返回“win32”。在 Windows 上,用户的主目录可能是 C:\Users[USERNAME] 或 C:\Documents and Settings[USERNAME],具体取决于所使用的 Windows 版本。在 Unix 上,这不是问题。

回答by maerics

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

正如在最近的回答中提到的,现在首选的方法很简单:

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

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

【原答案】USERPROFILEwin32上为什么不用环境变量?

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

回答by Cody Allan Taylor

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

os.homedir()由此 PR添加,是 nodejs 公共 4.0.0 版本的一部分。



Example usage:

用法示例:

const os = require('os');

console.log(os.homedir());

回答by Oncle Tom

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.

好吧,依靠特征而不是变量值会更准确。特别是因为 Windows 有 2 个可能的变量。

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

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

编辑:正如在最近的回答中提到的,https://stackoverflow.com/a/32556337/103396是正确的方法(require('os').homedir())。

回答by Andrew De Andrade

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

使用osenv.home(). 它由 isaacs 维护,我相信由 npm 本身使用。

https://github.com/isaacs/osenv

https://github.com/isaacs/osenv

回答by aH6y

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