1var isWindows = process.platform === 'win32' 2var path = require('path') 3var exec = require('child_process').exec 4var osTmpdir = require('os-tmpdir') 5var osHomedir = require('os-homedir') 6 7// looking up envs is a bit costly. 8// Also, sometimes we want to have a fallback 9// Pass in a callback to wait for the fallback on failures 10// After the first lookup, always returns the same thing. 11function memo (key, lookup, fallback) { 12 var fell = false 13 var falling = false 14 exports[key] = function (cb) { 15 var val = lookup() 16 if (!val && !fell && !falling && fallback) { 17 fell = true 18 falling = true 19 exec(fallback, function (er, output, stderr) { 20 falling = false 21 if (er) return // oh well, we tried 22 val = output.trim() 23 }) 24 } 25 exports[key] = function (cb) { 26 if (cb) process.nextTick(cb.bind(null, null, val)) 27 return val 28 } 29 if (cb && !falling) process.nextTick(cb.bind(null, null, val)) 30 return val 31 } 32} 33 34memo('user', function () { 35 return ( isWindows 36 ? process.env.USERDOMAIN + '\\' + process.env.USERNAME 37 : process.env.USER 38 ) 39}, 'whoami') 40 41memo('prompt', function () { 42 return isWindows ? process.env.PROMPT : process.env.PS1 43}) 44 45memo('hostname', function () { 46 return isWindows ? process.env.COMPUTERNAME : process.env.HOSTNAME 47}, 'hostname') 48 49memo('tmpdir', function () { 50 return osTmpdir() 51}) 52 53memo('home', function () { 54 return osHomedir() 55}) 56 57memo('path', function () { 58 return (process.env.PATH || 59 process.env.Path || 60 process.env.path).split(isWindows ? ';' : ':') 61}) 62 63memo('editor', function () { 64 return process.env.EDITOR || 65 process.env.VISUAL || 66 (isWindows ? 'notepad.exe' : 'vi') 67}) 68 69memo('shell', function () { 70 return isWindows ? process.env.ComSpec || 'cmd' 71 : process.env.SHELL || 'bash' 72}) 73