Package Exports
- xdg-app-paths
 - xdg-app-paths/cjs
 - xdg-app-paths/package.json
 
Readme
xdg-app-paths
Determine (XDG-compatible) paths for storing application files (cache, config, data, etc)
Installation (CJS/ESM/TypeScript)
npm install xdg-app-paths
# or... `npm install "git:github.com/rivy/js.xdg-app-paths"`
# or... `npm install "git:github.com/rivy/js.xdg-app-paths#v6.0.0"`
# or... `npm install "https://cdn.jsdelivr.net/gh/rivy/js.xdg-app-paths/dist/xdg-app-paths.tgz"`Usage
CommonJS (CJS)
// MyApp.js
const xdgAppPaths = require('xdg-app-paths/cjs');
const cache = xdgAppPaths.cache();
//(nix)=> '/home/rivy/.cache/MyApp.js'
//(win)=> 'C:\\Users\\rivy\\AppData\\Local\\MyApp\\Cache'
const config = xdgAppPaths.config();
//(nix)=> '/home/rivy/.config/MyApp.js'
//(win)=> 'C:\\Users\\rivy\\AppData\\Roaming\\MyApp\\Config'
const data = xdgAppPaths.data();
//(nix)=> '/home/rivy/.local/share/MyApp.js'
//(win)=> 'C:\\Users\\rivy\\AppData\\Roaming\\MyApp\\Data'ECMAScript (ESM)/TypeScript
import xdgAppPaths from 'xdg-app-paths';
const configDirs = xdgAppPaths.configDirs();
//...Deno
import xdgAppPaths from 'https://deno.land/x/xdg_app_paths/src/mod.deno.ts';
//or...
//import xdg from 'https://deno.land/x/xdg_app_paths@v9.0.0/src/mod.deno.ts';
//or (via CDN, with optional version/version-range/latest/commit support)...
//import osPaths from 'https://cdn.jsdelivr.net/gh/rivy/js.xdg-app-paths@7.0.0/src/mod.deno.ts'; // v7.0.0
//import osPaths from 'https://cdn.jsdelivr.net/gh/rivy/js.xdg-app-paths@7/src/mod.deno.ts'; // v7.x.y
//import osPaths from 'https://cdn.jsdelivr.net/gh/rivy/js.xdg-app-paths/src/mod.deno.ts'; // latest
//import osPaths from 'https://cdn.jsdelivr.net/gh/rivy/js.xdg-app-paths@latest/src/mod.deno.ts'; // latest
//import osPaths from 'https://cdn.jsdelivr.net/gh/rivy/js.xdg-app-paths@COMMIT/src/mod.deno.ts'; // commit
const configDirs = xdgAppPaths.configDirs();
//...Required Deno permissions
--allow-env (allow access to the process environment variables)
This module/package requires access to various environment variable to determine platform and user configuration (eg, XDG configuration variables, location of temp and user directories, ...).
API
Construction/Initialization
XDGAppPaths( Options? )
// CJS
const xdgAppPaths = require('xdg-app-paths/cjs');
// or ...
const xdgAppPaths = require('xdg-app-paths/cjs')(options);
// ESM/TypeScript
import xdgAppPaths from 'xdg-app-paths';
// or ...
import XDGAppPaths from 'xdg-app-paths';
const xdgAppPaths = XDGAppPaths(options);
// Deno
import xdgAppPaths from 'https://deno.land/x/xdg_app_paths/src/mod.deno.ts';
// or ...
import XDGAppPaths from 'https://deno.land/x/xdg_app_paths/src/mod.deno.ts';
const xdgAppPaths = XDGAppPaths(options);When importing this module, the object returned is a function object, XDGAppPaths, augmented with attached methods. Additional XDGAppPaths objects may be constructed by direct call of the imported XDGAppPaths object (eg, const x = xdgAppPaths(...)) or by using new (eg, const x = new xdgAppPaths(...)).
Upon construction, if not supplied with a specified name (via Options.name), XDGAppPaths will generate an application name which is used to further generate isolated application directories, where needed. "an-anonymous-script" is used as the fallback value when automatically generating names (ie, for immediate mode scripts such as node -e "..."). The generated or supplied name is stored during XDGAppPaths construction and subsequently accessible via the $name() method.
Types
import type { DirOptions, Options, XDGAppPaths } from 'xdg-app-paths'; // TypeScript
//or...
//import type { DirOptions, Options, XDGAppPaths } from 'https://deno.land/x/xdg_app_paths/src/mod.deno.ts'; // DenoXDGAppPaths
Primary module-supplied function object
Options
Configuration options supplied when constructing XDGAppPaths; (optional)
Options: string=>{ name: string }
As a shortcut, whenOptionsis supplied as astring, is interpreted directly as thenameproperty (ie,options = { name: options }).
Options: object
• default ={ name: '', suffix: '', isolated: true }
Options.name: string
• default =''
Name of your application; used to generate the paths
If missing (undefined),null, or empty (''), it is generated automatically from the available process information.
Options.suffix: string
• default =''
Suffix which is appended to the application name when generating the application paths
Options.isolated: boolean
• default =true
Default isolation flag (used when no isolation flag is supplied forDirOptions)
DirOptions
Configuration options supplied to XDGAppPaths methods; (optional)
DirOptions: boolean=>{ isolated: boolean }
As a shortcut, whenDirOptionsis supplied as aboolean, it is directly interpreted as theisolatedproperty (ie,dirOptions = { isolated: dirOptions }).
DirOptions: object
• default ={ isolated: true }
DirOptions.isolated: boolean
• default =true
Isolation flag; used to override the default isolation mode, when needed
Types named here are exported individually by name (eg, as "XDGAppPaths").
Methods
All returned path strings are simple, platform-compatible, strings and are not guaranteed to exist. The application is responsible for construction of the directories. If needed, make-dir or mkdirp can be used to create the directories.
xdgAppPaths.cache( DirOptions? ): string
Returns the directory for non-essential data files
Deletion of the data contained here might cause an application to slow down.
xdgAppPaths.config( DirOptions? ): string
Returns the directory for config files
Deletion of the data contained here might require the user to reconfigure an application.
xdgAppPaths.data( DirOptions? ): string
Returns the directory for data files
Deletion of the data contained here might force the user to restore from backups.
xdgAppPaths.runtime( DirOptions? ): string?
Returns the directory for runtime files; may return undefined
Deletion of the data contained here might interfere with a currently executing application but should have no effect on future executions.
xdgAppPaths.state( DirOptions? ): string
Returns the directory for state files
Deletion of the data contained here should not materially interfere with execution of an application.
xdgAppPaths.configDirs( DirOptions? ): readonly string[]
Returns a priority-sorted list of possible directories for configuration file storage (includes paths.config() as the first entry)
xdgAppPaths.dataDirs( DirOptions? ): readonly string[]
Returns a priority-sorted list of possible directories for data file storage (includes paths.data() as the first entry)
xdgAppPaths.$name(): string
Application name used for path construction (from supplied configuration or auto-generated)
xdgAppPaths.$isolated(): boolean
Default isolation mode used by the particular XDGAppPaths instance
Example
// MyApp.js
const locatePath = require('locate-path');
const mkdirp = require('mkdirp');
const path = require('path');
const xdgAppPaths = require('xdg-app-paths/cjs');
// Extend appPaths with a "log" location function
xdgAppPaths.log = function (dirOptions) {
  const self = xdgAppPaths; // * bind `self` to `xdgAppPaths` => avoids `this` variability due to caller context
  function typeOf(x) {
    // use avoids circumvention of eslint variable tracking for `x`
    return typeof x;
  }
  if (typeOf(dirOptions) === 'boolean') {
    dirOptions = { isolated: dirOptions };
  }
  if (
    typeOf(dirOptions) !== 'object' ||
    dirOptions === null ||
    typeOf(dirOptions.isolated) !== 'boolean'
  ) {
    dirOptions = { isolated: self.$isolated() };
  }
  return path.join(self.state(dirOptions), (dirOptions.isolated ? '' : self.$name() + '-') + 'log');
};
// log file
const logPath = path.join(xdgAppPaths.log(), 'debug.txt');
mkdirp.sync(path.dirname(logPath), 0o700);
// config file
// * search for config file within user preferred directories; otherwise, use preferred directory
const possibleConfigPaths = xdgAppPaths
  .configDirs()
  .concat(xdgAppPaths.configDirs({ isolated: !xdgAppPaths.$isolated() }))
  .map((v) => path.join(v, xdgAppPaths.$name() + '.json'));
const configPath = locatePath.sync(possibleConfigPaths) || possibleConfigPaths[0];
// debug(logPath, 'configPath="%s"', configPath);
mkdirp.sync(path.dirname(configPath), 0o700);
// cache file
const cacheDir = path.join(xdgAppPaths.cache());
// debug(logPath, 'cacheDir="%s"', cacheDir);
mkdirp.sync(cacheDir, 0o700);
const cachePath = {};
cachePath.orders = path.join(cacheDir, 'orders.json');
cachePath.customers = path.join(cacheDir, 'customers.json');
//...Supported Platforms
NodeJS
Requirements
NodeJS >= 4.0[^*]
[^*]: With the conversion to a TypeScript-based project, due to tooling constraints, building and testing are more difficult and more limited on Node platforms earlier than NodeJS-v10. However, the generated CommonJS/UMD project code is fully tested (for NodeJS-v10+) and continues to be compatible with NodeJS-v4+.
CommonJS modules (CJS; *.js and *.cjs)
CJS is the basic supported output (with support for NodeJS versions as early as NodeJS-v4).
const xdgAppPaths = require('xdg-app-paths/cjs');
console.log(xdgAppPaths.config());Note: for CJS,
require('xdg-app-paths')is supported for backward-compatibility and will execute correctly at run-time. However,require('xdg-app-paths')links to the default package type declarations which, though correct for ESM or TypeScript, are incorrect for CJS. This, then, leads to incorrect analysis of CJS files by static analysis tools such as TypeScript and Intellisense.Using
require('xdg-app-paths/cjs')is preferred as it associates the proper CJS type declarations and provides correct information to static analysis tools.
ECMAScript modules (ESM; *.mjs)
- Requires 
v6.0+. 
XDG fully supports ESM imports.
import xdgAppPaths from 'xdg-app-paths';
console.log(xdgAppPaths.config());TypeScript (*.ts)
- Requires 
v6.0+. 
As of v6.0+, XDG has been converted to a TypeScript-based module.
As a consequence, TypeScript type definitions are automatically generated, bundled, and exported by the module.
Deno
- Requires 
v7.0+. 
XDGAppPaths also fully supports use by Deno.
import xdgAppPaths from 'https://deno.land/x/xdg_app_paths/src/mod.deno.ts';
console.log(xdgAppPaths.config());Discussion
The XDG Base Directory Specification@ defines categories of user information (ie, "cache", "config", "data", ...), defines their standard storage locations, and defines the standard process for user configuration of those locations (using XDG_CACHE_HOME, etc).
Applications supporting the XDG convention are expected to store user-specific files within these locations, either within the common/shared directory (eg, `${xdg.cache()}/filename`) or within a more isolated application-defined subdirectory (eg, `${xdg.config()/dir/filename`; dir usually being the application name).
Windows ("win32") specific notes
Windows has an alternate convention, offering just two standard locations for applications to persist data, either %APPDATA% (for files which may "roam" with the user between hosts) and %LOCALAPPDATA% (for local-machine-only files). All application files are expected to be stored within an application-unique subdirectory in one of those two locations, usually under a directory matching the application name. There is no further popular convention used to segregate the file types (ie, into "cache", "config", ...) in any way similar to the XDG specification.
So, to support basic XDG-like behavior (that is, segregating the information types into type-specific directories), this module supports a new convention for Windows hosts (taken from xdg-portable), placing the specific types of files into subdirectories under either %APPDATA% or %LOCALAPPDATA%, as appropriate for the file type. The default directories used for the windows platform are listed by xdg-portable.
By default, this module returns paths which are isolated, application-specific sub-directories under the respective common/shared base directories. These sub-directories are purely dedicated to use by the application. If, however, the application requires access to the common/shared areas, the isolated: false option may be used during initialization (or as an optional override for specific function calls) to generate and return the common/shared paths. Note, that when using the command/shared directories, take care to use file names which do not collide with those used by other applications.
Origins
This module was forked from sindresorhus/env-paths in order to add cross-platform portability and support simpler cross-platform applications.
Building and Contributing
Build requirements
optional
git-changelog(v1.1+) ... enables changelog automation
Build/test
npm install-testProject development scripts
> npm run help
...
usage: `npm run TARGET` or `npx run-s TARGET [TARGET..]`
TARGETs:
build               build/compile package
clean               remove build artifacts
coverage            calculate and display (or send) code coverage [alias: 'cov']
fix                 fix package issues (automated/non-interactive)
fix:lint            fix ESLint issues
fix:style           fix Prettier formatting issues
help                display help
lint                check for package code 'lint'
lint:commits        check for commit flaws (using `commitlint` and `cspell`)
lint:editorconfig   check for EditorConfig format flaws (using `editorconfig-checker`)
lint:lint           check for code 'lint' (using `eslint`)
lint:markdown       check for markdown errors (using `remark`)
lint:spell          check for spelling errors (using `cspell`)
lint:style          check for format imperfections (using `prettier`)
realclean           remove all generated files
rebuild             clean and (re-)build project
retest              clean and (re-)test project
reset:hard          remove *all* generated files and reinstall dependencies
show:deps           show package dependencies
test                test package
test:code           test package code
test:types          test for type declaration errors (using `tsd`)
update              update/prepare for distribution [alias: 'dist']
update:changelog    update CHANGELOG (using `git changelog ...`)
update:dist         update distribution contentContributions
Contributions are welcome.
Any pull requests should be based off of the default branch (master). And, whenever possible, please include tests for any new code, ensuring that local (via npm test) and remote CI testing passes.
By contributing to the project, you are agreeing to provide your contributions under the same license as the project itself.
Related
xdg-portable... XDG Base Directory paths (cross-platform)env-paths... inspiration for this module