index.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. 'use strict';
  2. const path = require('path');
  3. const os = require('os');
  4. const homedir = os.homedir();
  5. const tmpdir = os.tmpdir();
  6. const {env} = process;
  7. const macos = name => {
  8. const library = path.join(homedir, 'Library');
  9. return {
  10. data: path.join(library, 'Application Support', name),
  11. config: path.join(library, 'Preferences', name),
  12. cache: path.join(library, 'Caches', name),
  13. log: path.join(library, 'Logs', name),
  14. temp: path.join(tmpdir, name)
  15. };
  16. };
  17. const windows = name => {
  18. const appData = env.APPDATA || path.join(homedir, 'AppData', 'Roaming');
  19. const localAppData = env.LOCALAPPDATA || path.join(homedir, 'AppData', 'Local');
  20. return {
  21. // Data/config/cache/log are invented by me as Windows isn't opinionated about this
  22. data: path.join(localAppData, name, 'Data'),
  23. config: path.join(appData, name, 'Config'),
  24. cache: path.join(localAppData, name, 'Cache'),
  25. log: path.join(localAppData, name, 'Log'),
  26. temp: path.join(tmpdir, name)
  27. };
  28. };
  29. // https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
  30. const linux = name => {
  31. const username = path.basename(homedir);
  32. return {
  33. data: path.join(env.XDG_DATA_HOME || path.join(homedir, '.local', 'share'), name),
  34. config: path.join(env.XDG_CONFIG_HOME || path.join(homedir, '.config'), name),
  35. cache: path.join(env.XDG_CACHE_HOME || path.join(homedir, '.cache'), name),
  36. // https://wiki.debian.org/XDGBaseDirectorySpecification#state
  37. log: path.join(env.XDG_STATE_HOME || path.join(homedir, '.local', 'state'), name),
  38. temp: path.join(tmpdir, username, name)
  39. };
  40. };
  41. const envPaths = (name, options) => {
  42. if (typeof name !== 'string') {
  43. throw new TypeError(`Expected string, got ${typeof name}`);
  44. }
  45. options = Object.assign({suffix: 'nodejs'}, options);
  46. if (options.suffix) {
  47. // Add suffix to prevent possible conflict with native apps
  48. name += `-${options.suffix}`;
  49. }
  50. if (process.platform === 'darwin') {
  51. return macos(name);
  52. }
  53. if (process.platform === 'win32') {
  54. return windows(name);
  55. }
  56. return linux(name);
  57. };
  58. module.exports = envPaths;
  59. // TODO: Remove this for the next major release
  60. module.exports.default = envPaths;