node.js - 如何获取操作系统平台用户数据文件夹

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19275776/
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:54:59  来源:igfitidea点击:

node.js - how to get the OS platforms user data folder

node.js

提问by kabal

I am looking for a way to get the userdata folder using Node.js, that will work on both Windows and macOS.

我正在寻找一种使用 Node.js 获取 userdata 文件夹的方法,该方法适用于 Windows 和 macOS。

The Node.js instance would be running on the user's machine.

Node.js 实例将在用户的机器上运行。

I need something that returns the following:

我需要一些返回以下内容的东西:

  • C:\Documents and Settings\JohnD\Application Data(Windows XP)
  • C:\Users\JohnD\AppData\Roaming(Windows Vista and Up)
  • /Users/JohnD/Library/Preferences(macOS)
  • C:\Documents and Settings\JohnD\Application Data(Windows XP)
  • C:\Users\JohnD\AppData\Roaming(Windows Vista 及更高版本)
  • /Users/JohnD/Library/Preferences(苹果系统)

Is this possible?

这可能吗?

采纳答案by Andrei Karpushonak

You can check user environment which is stored in process.env

您可以检查存储在process.env 中的用户环境

Also, take a look at process.platform

另外,看看process.platform

To be specific:

再具体一点:

% node                                                                                                                                 
> console.log(process.env.HOME)
/Users/miktam
> console.log(process.platform)
darwin

Having this information, you will be able to achieve what you need.

有了这些信息,您将能够实现您的需求。

回答by Luke

Try the following:

请尝试以下操作:

process.env.APPDATA || (process.platform == 'darwin' ? process.env.HOME + '/Library/Preferences' : process.env.HOME + "/.local/share")

The expected result is:

预期的结果是:

OS X - '/Users/user/Library/Preferences'

OS X - '/Users/用户/Library/Preferences'

Windows 8 - 'C:\Users\user\AppData\Roaming'

Windows 8 - 'C:\Users\用户\AppData\Roaming'

Windows XP - 'C:\Documents and Settings\user\Application Data'

Windows XP - 'C:\Documents and Settings\ user\Application Data'

Linux - '/home/user/.local/share'

Linux - '/home/用户/.local/share'