You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

polyfill.js 1.8KB

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