Node.js - 以与平台无关的方式查找主目录
对于 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
正如 最近的答案中提到的,现在首选的方法很简单:
[原始答案] 为什么不使用
win32 上的 USERPROFILE
环境变量?As mentioned in a more recent answer, the preferred way is now simply:
[Original Answer] Why not use the
USERPROFILE
environment variable on win32?添加了
os.homedir()
此 PR,是 Nodejs 公共 4.0.0 版本的一部分。用法示例:
os.homedir()
was added by this PR and is part of the public 4.0.0 release of nodejs.Example usage:
嗯,依靠特征而不是变量值会更准确。特别是对于 Windows 有 2 个可能的变量。
编辑:正如最近的答案中提到的,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.
EDIT: as mentioned in a more recent answer, https://stackoverflow.com/a/32556337/103396 is the right way to go (
require('os').homedir()
).使用 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
在某些情况下尝试使用此:
或者
即在处理之前添加 this 或 this.nw
in some cases try to use this:
or
i.e. add this or this.nw before process