Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

node.js

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?

like image 847
kabal Avatar asked Oct 09 '13 15:10

kabal


People also ask

How do I find the User Data folder?

Windows. The default location is in the local app data folder: [Chrome] %LOCALAPPDATA%\Google\Chrome\User Data.

How do I find the directory of a node js file?

Using __dirname in a Node script will return the path of the folder where the current JavaScript file resides. Using ./ will give you the current working directory. It will return the same result as calling process.

How do I find my home directory in node JS?

To get the current user home directory, you can use the homedir() method from the os module in Node. js. /* Get home directory of the user in Node. js */ // import os module const os = require("os"); // check the available memory const userHomeDir = os.


2 Answers

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'

like image 101
Luke Avatar answered Oct 11 '22 22:10

Luke


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.

like image 40
Andrei Karpushonak Avatar answered Oct 11 '22 23:10

Andrei Karpushonak