xdg-portable

Determine XDG Base Directory paths (OS/platform portable)

Build status (GHA) Build status (Travis-CI) Build status (AppVeyor) Coverage status License Style Guide  
Repository Deno version NPM version NodeJS version npmJS Downloads JSDelivr Downloads

Installation (CJS/ESM/TypeScript)

npm install xdg-portable
# or... `npm install "git:github.com/rivy/js.xdg-portable"`
# or... `npm install "git:github.com/rivy/js.xdg-portable#v9.0.0"`
# or... `npm install "https://cdn.jsdelivr.net/gh/rivy/js.xdg-portable/dist/xdg-portable.tgz"`

Usage

CommonJS (CJS)

const xdg = require('xdg-portable/cjs');

const configDirs = xdg.configDirs();
const stateDir = xdg.state();

const locatePath = require('locatePath');
const mkdirp = require('mkdirp');

const configDir = locatePath.sync(configDirs) || configDirs[0];
mkdirp.sync(configDir, 0o700);

mkdirp.sync(stateDir, 0o700);

ECMAScript (ESM)/TypeScript

import xdg from 'xdg-portable';
const configDirs = xdg.configDirs();
//...

Deno

import xdg from 'https://deno.land/x/xdg/src/mod.deno.ts';
//or...
//import xdg from 'https://deno.land/x/xdg@v10.2.0/src/mod.deno.ts';
//or (via CDN, with optional version/version-range/latest/commit support)...
//import xdg from 'https://cdn.jsdelivr.net/gh/rivy/js.xdg-portable@10.2.0/src/mod.deno.ts'; // v10.2.0
//import xdg from 'https://cdn.jsdelivr.net/gh/rivy/js.xdg-portable@10/src/mod.deno.ts'; // v10.x.y
//import xdg from 'https://cdn.jsdelivr.net/gh/rivy/js.xdg-portable/src/mod.deno.ts'; // latest (*not* recommended for production by JSDelivr)
//import xdg from 'https://cdn.jsdelivr.net/gh/rivy/js.xdg-portable@latest/src/mod.deno.ts'; // latest
//import xdg from 'https://cdn.jsdelivr.net/gh/rivy/js.xdg-portable@COMMIT_SHA/src/mod.deno.ts'; // commit
const configDirs = xdg.configDirs();
//...

API

Construction/Initialization

XDG()

const xdg = require('xdg-portable/cjs'); // CJS
//or...
//import xdg from 'xdg-portable'; // ESM/TypeScript
//import xdg from 'https://deno.land/x/xdg/src/mod.deno.ts'; // Deno

When importing this module, the object returned is a function object, XDG, augmented with attached methods. Additional XDG objects may be constructed by direct call of the imported XDG object (eg, const x = xdg()) or by using new (eg, const x = new xdg()). Notably, since the XDG object contains no user-facing instance state, all XDG objects will be functionally identical.

Types

  • XDG ~ primary module function object

Types named here are exported individually by name (eg, as "XDG").

import type { XDG } from 'xdg-portable'; // TypeScript
//or...
//import type { XDG } from 'https://deno.land/x/xdg/src/mod.deno.ts'; // Deno

Methods

All module methods return platform-compatible path strings which are normalized and have no trailing path separators.

The returned path strings are not guaranteed to already exist on the file system. So, the user application is responsible for directory construction, if/when needed. If needed, make-dir or mkdirp can be used to create the directories.

xdg.cache(): string

  • Returns the directory path for user-specific non-essential (ie, cached) data files.

Deletion of the data contained here might cause an application to slow down.

const cacheDir = xdg.cache();
//(mac)=> '/Users/rivy/Library/Caches'
//(nix)=> '/home/rivy/.cache'
//(win)=> 'C:\\Users\\rivy\\AppData\\Local\\xdg.cache'

This directory location would be analogous to /var/cache for *nix.

%LocalAppData%\xdg.cache is the default for the windows platform.

xdg.config(): string

  • Returns the directory path for user-specific configuration files.

Deletion of the data contained here might require the user to reconfigure an application.

const configDir = xdg.config();
//(mac)=> '/Users/rivy/Library/Preferences'
//(nix)=> '/home/rivy/.config'
//(win)=> 'C:\\Users\\rivy\\AppData\\Roaming\\xdg.config'

This directory location would be analogous to /etc for *nix.

%AppData%\xdg.config is the default for the windows platform.

xdg.data(): string

  • Returns directory path for user-specific data files.

Deletion of the data contained here might force the user to restore from backups.

const dataDir = xdg.data();
//(mac)=> '/Users/rivy/Library/Application Support'
//(nix)=> '/home/rivy/.local/share'
//(win)=> 'C:\\Users\\rivy\\AppData\\Roaming\\xdg.data'

This directory location would be analogous to /usr/share for *nix.

%AppData%\xdg.data is the default for the windows platform.

xdg.runtime(): string?

  • Returns the directory path for user-specific non-essential runtime files (such as sockets, named pipes, etc); may be undefined.

Deletion of the data contained here might interfere with a currently executing application but should have no effect on future executions.

const runtimeDir = xdg.runtime();

The XDG specification defines some fairly strict specifications for a "runtime"-data candidate directory. To meet these criteria, the directory must usually be supplied by the OS. The user may override this by using the XDG_RUNTIME_DIR environment variable.

undefined is the default for the windows platform.

xdg.state(): string

  • Returns the directory path for user-specific state files (non-essential and more volatile than configuration files).

Deletion of the data contained here should not materially interfere with execution of an application.

const stateDir = xdg.state();
//(mac)=> '/Users/rivy/Library/State'
//(nix)=> '/home/rivy/.local/state'
//(win)=> 'C:\\Users\\rivy\\AppData\\Local\\xdg.state'

This directory location might hold data such as backups, input history, logs, recent file lists, visual application state, etc.

%LocalAppData%\xdg.state is the default for the windows platform.

xdg.configDirs(): readonly string[]

  • Returns a preference-ordered array of base directory paths to search for configuration files (includes xdg.config() directory as first entry).
const configDirs = xdg.configDirs();
//(mac)=> [ '/Users/rivy/Library/Preferences', ... ]
//(nix)=> [ '/home/rivy/.config', ... ]
//(win)=> [ 'C:\\Users\\rivy\\AppData\\Roaming\\xdg.config' , ... ]

xdg.dataDirs(): readonly string[]

  • Returns a preference-ordered array of base directory paths to search for data files (includes xdg.data() directory as first entry).
const dataDirs = xdg.dataDirs();
//(mac)=> [ '/Users/rivy/Library/Application Support', ... ]
//(nix)=> [ '/home/rivy/.local/share', ... ]
//(win)=> [ 'C:\\Users\\rivy\\AppData\\Roaming\\xdg.share' , ... ]

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 xdg = require('xdg-portable/cjs');
console.log(xdg.config());

Note: for CJS, require('xdg-portable') is supported for backward-compatibility and will execute correctly at run-time. However, require('xdg-portable') links to the default package type declarations which, though correct for Deno/ESM/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-portable/cjs') is preferred as it associates the proper CJS type declarations and provides correct information to static analysis tools.

ECMAScript modules (ESM; *.mjs)

  • Requires XDG v8.0+.

XDG fully supports ESM imports.

import xdg from 'xdg-portable';
console.log(xdg.config());

TypeScript (*.ts)

  • Requires XDG v8.0+.

As of v8.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

Requirements

Deno >= v1.8.0[^deno-version-req]

[^deno-version-req]: The Deno.permissions API (stabilized in Deno v1.8.0) is required to avoid needless panics or prompts by Deno during static imports of this module/package. Note: Deno v1.3.0+ may be used if the run flag --unstable is also used.

Required Permissions

  • --allow-env · allow access to the process environment variables
    This module/package requires access to various environment variables to determine platform configuration (eg, location of temp and user directories).
  • Requires XDG v9.0+.

XDG also fully supports use by Deno.

import xdg from 'https://deno.land/x/xdg/src/mod.deno.ts';
console.log(xdg.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 creates a new convention for Windows hosts, placing the specific types of files into subdirectories under either %APPDATA% or %LOCALAPPDATA%, as appropriate for the file type. For example, "cache"-type files will be offered placement into %LOCALAPPDATA%\xdg.cache, "config"-type files into %APPDATA%\xdg.config, "data"-type files into %APPDATA%\xdg.data, etc.

xdg-app-paths builds on this module and offers application specific paths more in-line with usual platform conventions, but still compatible with the XDG specification.

Fallback to temporary directory

In the uncommon case that both the XDG environment variable is not set and the users home directory can't be determined, the temporary directory (OS/platform specific; determined by temp() from os-paths) will be used as a fallback for the missing home directory value.

Origins

This module was forked from sindresorhus/xdg-basedir in order to add cross-platform portability and support simpler cross-platform applications.

Building and Contributing

Repository Build status (GHA) Build status (Travis-CI) Build status (AppVeyor) Coverage status  
Quality status (Codacy) Quality status (CodeClimate) Quality status (CodeFactor)

Build requirements

  • NodeJS >= 10.14
  • a JavaScript package/project manager (npm or yarn)
  • git

optional

  • git-changelog (v1.1+) ... enables changelog automation
  • perl ... enables automated version updates to package.json during packaging

Quick build/test

npm install-test

Contributions/development

Reproducible setup (for CI or local development)

git clone "https://github.com/rivy/js.xdg-portable"
cd js.os-paths
# * note: for WinOS, replace `cp` with `copy`
# npm
cp .deps-lock/package-lock.json .
npm clean-install
# yarn
cp .deps-lock/yarn.lock .
yarn --immutable --immutable-cache --check-cache

Project 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`)
prerelease          clean, rebuild, and fully test (useful prior to publish/release)
realclean           remove all generated files
rebuild             clean and (re-)build project
refresh             clean and rebuild/regenerate all project artifacts
refresh:dist        clean, rebuild, and regenerate project distribution
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 content
verify              fully (and verbosely) test package

Packaging & Publishing

Package
#=== * POSIX
# next VERSION in M.m.r (semver) format
VERSION=...
# update to VERSION in package.json
perl -i -E 'use open IO => q/:raw:utf8/} while(<>) { s/^(\s*\x22version\x22\s*:\s*)\x22(?:\d+(?:[.]\d+)*)?\x22/$1\x22$ENV{VERSION}\x22/ims; print }' package.json
git-changelog --next-tag "v${VERSION}" > CHANGELOG.mkd
# create/commit updates and distribution
git add package.json CHANGELOG.mkd
git commit -m "${VERSION}"
npm run clean && npm run update:dist
git add dist
git commit --amend --no-edit
# tag VERSION commit
git tag -f "v${VERSION}"
@rem ::# (optional) update/save dependency locks
npm install --package-lock
rm yarn.lock && yarn import
mkdir .deps-lock 2> /dev/null
cp package-lock.json .deps-lock/
cp yarn.lock .deps-lock/
# (optional) prerelease checkup
npm run prerelease
#=== * WinOS
@rem ::# next VERSION in M.m.r (semver) format
set VERSION=...
@rem ::# update to VERSION in package.json
perl -i -E "use open IO => q/:raw:utf8/; while(<>) { s/^(\s*\x22version\x22\s*:\s*)\x22(?:\d+(?:[.]\d+)*)?\x22/$1\x22$ENV{VERSION}\x22/ims; print }" package.json
git-changelog --next-tag "v%VERSION%" > CHANGELOG.mkd
@rem ::# create/commit updates and distribution
git add package.json CHANGELOG.mkd
git commit -m "%VERSION%"
npm run clean && npm run update:dist
git add dist
git commit --amend --no-edit
@rem ::# tag VERSION commit
git tag -f "v%VERSION%"
@rem ::# (optional) update/save dependency locks
npm install --package-lock
del yarn.lock && yarn import
mkdir .deps-lock 2>NUL
copy /y package-lock.json .deps-lock
copy /y yarn.lock .deps-lock
@rem ::# (optional) prerelease checkup
npm run prerelease
Publish
# publish
# * optional (will be done in 'prePublishOnly' by `npm publish`)
npm run clean && npm run test && npm run dist && git-changelog > CHANGELOG.mkd
npm run _:v_tag:exists || echo "[lint] ERROR Missing version matching commit tag" # expect no output and exit code == 0
git diff-index --quiet HEAD || echo "[lint] ERROR uncommitted changes" # expect no output and exit code == 0
# *
npm publish # `npm publish --dry-run` will perform all prepublication actions and stop just before the actual publish push
# * if published to NPMjs with no ERRORs; push to deno.land with tag push
git push origin --tags

Contributions

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.

License

MIT © Roy Ivy III