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

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

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

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)

Is this possible?


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'

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

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

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


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

Also, take a look at 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.