Node.js | os.homedir() Method

The os.homedir() method is an inbuilt application programming interface of the os module which is used to get path of the home directory for the current user.

Syntax:

os.homedir()

Parameters: This method does not accept any parameters.



Return Value: This method returns a string specifies the path of the home directory for the current user.

  • On windows, It collects its value from an environment variable called USERPROFILE if defined. Otherwise, it returns the path to the profile directory for the current user.
  • On POSIX, It collects its value from an environment variable called $HOME if defined. Otherwise, it returns the home directory for some effective UID.

Below examples illustrate the use of os.homedir() method in Node.js:

Example 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the   
// os.homedir() method
  
// Allocating os module
const os = require('os');
  
// Printing os.homedir() value
console.log(os.homedir());

chevron_right


Output:

C:\Users\gekcho

Example 2: Alternative way to find home directory

filter_none

edit
close

play_arrow

link
brightness_4
code

// Node.js program to demonstrate the   
// os.homedir() method
  
// Allocating os module
const os = require('os');
  
console.log(getUserHome());
   
function getUserHome() {
      
    // Return the value using process.env
    return process.env[(process.platform == 
          'win32') ? 'USERPROFILE' : 'HOME'];
}

chevron_right


Output:

C:\Users\gekcho

Note: The above program will compile and run by using the node index.js command.

Reference: https://nodejs.org/api/os.html#os_os_homedir



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.