index.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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.env;
  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.LOCALAPPDATA || path.join(homedir, 'AppData', 'Local');
  19. return {
  20. // data/config/cache/log are invented by me as Windows isn't opinionated about this
  21. data: path.join(appData, name, 'Data'),
  22. config: path.join(appData, name, 'Config'),
  23. cache: path.join(appData, name, 'Cache'),
  24. log: path.join(appData, name, 'Log'),
  25. temp: path.join(tmpdir, name)
  26. };
  27. };
  28. // https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
  29. const linux = name => {
  30. const username = path.basename(homedir);
  31. return {
  32. data: path.join(env.XDG_DATA_HOME || path.join(homedir, '.local', 'share'), name),
  33. config: path.join(env.XDG_CONFIG_HOME || path.join(homedir, '.config'), name),
  34. cache: path.join(env.XDG_CACHE_HOME || path.join(homedir, '.cache'), name),
  35. // https://wiki.debian.org/XDGBaseDirectorySpecification#state
  36. log: path.join(env.XDG_STATE_HOME || path.join(homedir, '.local', 'state'), name),
  37. temp: path.join(tmpdir, username, name)
  38. };
  39. };
  40. module.exports = (name, opts) => {
  41. if (typeof name !== 'string') {
  42. throw new TypeError(`Expected string, got ${typeof name}`);
  43. }
  44. opts = Object.assign({suffix: 'nodejs'}, opts);
  45. if (opts.suffix) {
  46. // add suffix to prevent possible conflict with native apps
  47. name += `-${opts.suffix}`;
  48. }
  49. if (process.platform === 'darwin') {
  50. return macos(name);
  51. }
  52. if (process.platform === 'win32') {
  53. return windows(name);
  54. }
  55. return linux(name);
  56. };