| Leo Repp | 58b9f11 | 2021-11-22 11:57:47 +0100 | [diff] [blame^] | 1 | 'use strict'; |
| 2 | |
| 3 | var fs = require('fs'); |
| 4 | var parse = require('parse-passwd'); |
| 5 | |
| 6 | function homedir() { |
| 7 | // The following logic is from looking at logic used in the different platform |
| 8 | // versions of the uv_os_homedir function found in https://github.com/libuv/libuv |
| 9 | // This is the function used in modern versions of node.js |
| 10 | |
| 11 | if (process.platform === 'win32') { |
| 12 | // check the USERPROFILE first |
| 13 | if (process.env.USERPROFILE) { |
| 14 | return process.env.USERPROFILE; |
| 15 | } |
| 16 | |
| 17 | // check HOMEDRIVE and HOMEPATH |
| 18 | if (process.env.HOMEDRIVE && process.env.HOMEPATH) { |
| 19 | return process.env.HOMEDRIVE + process.env.HOMEPATH; |
| 20 | } |
| 21 | |
| 22 | // fallback to HOME |
| 23 | if (process.env.HOME) { |
| 24 | return process.env.HOME; |
| 25 | } |
| 26 | |
| 27 | return null; |
| 28 | } |
| 29 | |
| 30 | // check HOME environment variable first |
| 31 | if (process.env.HOME) { |
| 32 | return process.env.HOME; |
| 33 | } |
| 34 | |
| 35 | // on linux platforms (including OSX) find the current user and get their homedir from the /etc/passwd file |
| 36 | var passwd = tryReadFileSync('/etc/passwd'); |
| 37 | var home = find(parse(passwd), getuid()); |
| 38 | if (home) { |
| 39 | return home; |
| 40 | } |
| 41 | |
| 42 | // fallback to using user environment variables |
| 43 | var user = process.env.LOGNAME || process.env.USER || process.env.LNAME || process.env.USERNAME; |
| 44 | |
| 45 | if (!user) { |
| 46 | return null; |
| 47 | } |
| 48 | |
| 49 | if (process.platform === 'darwin') { |
| 50 | return '/Users/' + user; |
| 51 | } |
| 52 | |
| 53 | return '/home/' + user; |
| 54 | } |
| 55 | |
| 56 | function find(arr, uid) { |
| 57 | var len = arr.length; |
| 58 | for (var i = 0; i < len; i++) { |
| 59 | if (+arr[i].uid === uid) { |
| 60 | return arr[i].homedir; |
| 61 | } |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | function getuid() { |
| 66 | if (typeof process.geteuid === 'function') { |
| 67 | return process.geteuid(); |
| 68 | } |
| 69 | return process.getuid(); |
| 70 | } |
| 71 | |
| 72 | function tryReadFileSync(fp) { |
| 73 | try { |
| 74 | return fs.readFileSync(fp, 'utf8'); |
| 75 | } catch (err) { |
| 76 | return ''; |
| 77 | } |
| 78 | } |
| 79 | |
| 80 | module.exports = homedir; |
| 81 | |