homedir.js (2326B)
1 /** 2 * @license Apache-2.0 3 * 4 * Copyright (c) 2018 The Stdlib Authors. 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 'use strict'; 20 21 // MODULES // 22 23 var ENV = require( '@stdlib/process/env' ); 24 var IS_WINDOWS = require( '@stdlib/assert/is-windows' ); 25 var PLATFORM = require( './../../platform' ); 26 var getuid = require( '@stdlib/process/getuid' ); 27 28 29 // MAIN // 30 31 /** 32 * Returns the current user's home directory. 33 * 34 * @returns {(string|null)} home directory 35 * 36 * @example 37 * var home = homedir(); 38 * // e.g., returns '/Users/<username>' 39 */ 40 function homedir() { 41 var home; 42 var user; 43 44 if ( IS_WINDOWS ) { 45 // https://github.com/libuv/libuv/blob/764877fd9e4ea67c0cbe27bf81b2b294ed33b0f5/src/win/util.c#L1170 46 // https://en.wikipedia.org/wiki/Environment_variable#Windows 47 home = ENV[ 'USERPROFILE' ] || ENV[ 'HOMEDRIVE' ]+ENV[ 'HOMEPATH' ] || ENV[ 'HOME' ]; 48 return ( home ) ? home : null; // eslint-disable-line no-unneeded-ternary 49 } 50 // https://github.com/libuv/libuv/blob/9fbcca048181b927cfcdb5c6c49e5bdff173aad5/src/unix/core.c#L1030 51 home = ENV[ 'HOME' ]; 52 if ( home ) { 53 return home; 54 } 55 // Get the current user account (https://docs.python.org/2/library/getpass.html): 56 user = ENV[ 'LOGNAME' ] || ENV[ 'USER' ] || ENV[ 'LNAME' ] || ENV[ 'USERNAME' ]; 57 58 // If on Mac OS X, use the Mac path convention (http://apple.stackexchange.com/questions/119230/what-is-standard-for-os-x-filesystem-e-g-opt-vs-usr)... 59 if ( PLATFORM === 'darwin' ) { 60 return ( user ) ? '/Users/'+user : null; 61 } 62 // Check if running as 'root' (https://en.wikipedia.org/wiki/Filesystem_Hierarchy_Standard)... 63 if ( getuid() === 0 ) { 64 return '/root'; 65 } 66 // If on Linux, use the Linux path convention (https://en.wikipedia.org/wiki/Filesystem_Hierarchy_Standard)... 67 return ( user ) ? '/home/'+user : null; 68 } 69 70 71 // EXPORTS // 72 73 module.exports = homedir;