Skip to content
Related Articles

Related Articles

Node.js os.homedir() Method

View Discussion
Improve Article
Save Article
  • Last Updated : 13 Oct, 2021
View Discussion
Improve Article
Save Article

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:




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


Output:

C:\Users\gekcho

Example 2: Alternative way to find home directory




// 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'];
}


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
Recommended Articles
Page :

Start Your Coding Journey Now!