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:
javascript
Output:
javascript
Output:
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
USERPROFILEif 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
$HOMEif defined. Otherwise, it returns the home directory for some effective UID.
// Node.js program to demonstrate the
// os.homedir() method
// Allocating os module
const os = require('os');
// Printing os.homedir() value
console.log(os.homedir());
C:\Users\gekchoExample 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'];
}
C:\Users\gekchoNote: The above program will compile and run by using the
node index.js command.
Reference: https://nodejs.org/api/os.html#os_os_homedir