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

发布于 2025-01-01 04:47:08 字数 159 浏览 5 评论 0原文

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

清风无影 2025-01-08 04:47:08

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

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

[原始答案] 为什么不使用 win32 上的 USERPROFILE 环境变量?

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

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'];
}
二货你真萌 2025-01-08 04:47:08

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


用法示例:

const os = require('os');

console.log(os.homedir());

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());
筱武穆 2025-01-08 04:47:08

嗯,依靠特征而不是变量值会更准确。特别是对于 Windows 有 2 个可能的变量。

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

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

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()).

放我走吧 2025-01-08 04:47:08

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

https://github.com/isaacs/osenv

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

https://github.com/isaacs/osenv

混吃等死 2025-01-08 04:47:08
getUserRootFolder() {
  return process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
}
getUserRootFolder() {
  return process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
}
留蓝 2025-01-08 04:47:08

在某些情况下尝试使用此:

this.process.env.USERPROFILE

或者

this.nw.process.env.USERPROFILE

即在处理之前添加 this 或 this.nw

in some cases try to use this:

this.process.env.USERPROFILE

or

this.nw.process.env.USERPROFILE

i.e. add this or this.nw before process

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文