Open In App

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.



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

Article Tags :