3 var os = require('os');
4 var fs = require('fs');
5 var parse = require('parse-passwd');
8 // The following logic is from looking at logic used in the different platform
9 // versions of the uv_os_homedir function found in https://github.com/libuv/libuv
10 // This is the function used in modern versions of node.js
12 if (process.platform === 'win32') {
13 // check the USERPROFILE first
14 if (process.env.USERPROFILE) {
15 return process.env.USERPROFILE;
18 // check HOMEDRIVE and HOMEPATH
19 if (process.env.HOMEDRIVE && process.env.HOMEPATH) {
20 return process.env.HOMEDRIVE + process.env.HOMEPATH;
24 if (process.env.HOME) {
25 return process.env.HOME;
31 // check HOME environment variable first
32 if (process.env.HOME) {
33 return process.env.HOME;
36 // on linux platforms (including OSX) find the current user and get their homedir from the /etc/passwd file
37 var passwd = tryReadFileSync('/etc/passwd');
38 var home = find(parse(passwd), getuid());
43 // fallback to using user environment variables
44 var user = process.env.LOGNAME || process.env.USER || process.env.LNAME || process.env.USERNAME;
50 if (process.platform === 'darwin') {
51 return '/Users/' + user;
54 return '/home/' + user;
57 function find(arr, uid) {
59 for (var i = 0; i < len; i++) {
60 if (+arr[i].uid === uid) {
61 return arr[i].homedir;
67 if (typeof process.geteuid === 'function') {
68 return process.geteuid();
70 return process.getuid();
73 function tryReadFileSync(fp) {
75 return fs.readFileSync(fp, 'utf8');
81 if (typeof os.homedir === 'undefined') {
82 module.exports = homedir;
84 module.exports = os.homedir;