Initial commit
[yaffs-website] / node_modules / homedir-polyfill / index.js
1 'use strict';
2
3 var os = require('os');
4 var fs = require('fs');
5 var parse = require('parse-passwd');
6
7 function homedir() {
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
11
12   if (process.platform === 'win32') {
13     // check the USERPROFILE first
14     if (process.env.USERPROFILE) {
15       return process.env.USERPROFILE;
16     }
17
18     // check HOMEDRIVE and HOMEPATH
19     if (process.env.HOMEDRIVE && process.env.HOMEPATH) {
20       return process.env.HOMEDRIVE + process.env.HOMEPATH;
21     }
22
23     // fallback to HOME
24     if (process.env.HOME) {
25       return process.env.HOME;
26     }
27
28     return null;
29   }
30
31   // check HOME environment variable first
32   if (process.env.HOME) {
33     return process.env.HOME;
34   }
35
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());
39   if (home) {
40     return home;
41   }
42
43   // fallback to using user environment variables
44   var user = process.env.LOGNAME || process.env.USER || process.env.LNAME || process.env.USERNAME;
45
46   if (!user) {
47     return null;
48   }
49
50   if (process.platform === 'darwin') {
51     return '/Users/' + user;
52   }
53
54   return '/home/' + user;
55 }
56
57 function find(arr, uid) {
58   var len = arr.length;
59   for (var i = 0; i < len; i++) {
60     if (+arr[i].uid === uid) {
61       return arr[i].homedir;
62     }
63   }
64 }
65
66 function getuid() {
67   if (typeof process.geteuid === 'function') {
68     return process.geteuid();
69   }
70   return process.getuid();
71 }
72
73 function tryReadFileSync(fp) {
74   try {
75     return fs.readFileSync(fp, 'utf8');
76   } catch (err) {
77     return '';
78   }
79 }
80
81 if (typeof os.homedir === 'undefined') {
82   module.exports = homedir;
83 } else {
84   module.exports = os.homedir;
85 }