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:
const os = require( 'os' );
console.log(os.homedir());
|
Output:
C:\Users\gekcho
Example 2: Alternative way to find home directory
const os = require( 'os' );
console.log(getUserHome());
function getUserHome() {
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