rc9

repository·main·Indexed 43 days ago

https://github.com/unjs/rc9

A lightweight utility for reading and writing configuration files (rc files) with support for nested objects via dot notation, automatic type conversion via destr, and XDG-compliant user configuration management. Version 3.1.0 provides a comprehensive API including read, write, update, and parse functions for managing .conf files and user-level configuration directories.

Tokens
2.3K
Snippets
10
Records
14
Agent score
5%

What's inside rc9

  1. How unflattening works in RC9

    main

    RC9 uses the flat package to automatically flatten and unflatten objects when reading and writing. This allows you to use dot notation in your config files to represent nested objects.

    Examples:

    • hello.world = true becomes { hello: { world: true } }
    • test.0 = A becomes { test: ['A'] } (using array indices)
    • test[]=A pushes A to the test array.

    Disabling unflattening: If you have keys that might conflict (e.g., x= and x.y=), you can disable this behavior by passing { flat: true } in the RCOptions object.

    // To disable unflattening:
    read({ flat: true });
  2. How native values are handled in RC9

    main

    RC9 uses destr to automatically convert configuration values into native JavaScript types.

    For example, count=123 in a config file will be parsed as the number 123 rather than the string "123".

    Preserving strings: If you need a value to remain a string, wrap it in quotes in your configuration file: count="123"

  3. Install RC9

    main

    You can install rc9 using your preferred package manager. Use npx nypm install rc9 to automatically detect your package manager.

    # npm
    npm install rc9
    
    # yarn
    yarn add rc9
    
    # pnpm
    pnpm add rc9
    
    # bun
    bun install rc9
    
    # deno
    deno install npm:rc9
    npx nypm install rc9
  4. Read and write configuration files

    main

    RC9 provides simple functions to read and write configuration files. By default, it looks for a file named .conf in the current working directory.

    To read a config file:

    const config = read(); // Reads default '.conf'
    // or
    const config = read('.conf');

    To write a config file:

    const config = { enabled: false };
    write(config); // Writes to default '.conf'
    // or
    write(config, '.conf');
    const config = read();
    config.enabled = false;
    write(config);
  5. Update configuration values

    main

    Use the update function to modify specific keys in your configuration without manually reading and writing the whole object. You can use dot notation for nested keys.

    To update a nested key:

    update({ "db.enabled": false });

    To push a value to an array, use the [] suffix on the key:

    update({ "modules[]": "test" });
  6. Manage user configuration via XDG directories

    main

    To store configuration in the user's standard config directory (e.g., $XDG_CONFIG_HOME or ~/.config), use the UserConfig suite of functions. This is preferred over the deprecated readUser/writeUser/updateUser functions.

    // Write to ~/.config/.zoorc
    writeUserConfig({ token: 123 }, ".zoorc");
    
    // Read from ~/.config/.zoorc
    const conf = readUserConfig(".zoorc");
    
    // Update ~/.config/.zoorc
    updateUserConfig({ token: 456 }, ".zoorc");

    Use userConfigDir() to retrieve the path to the user's configuration directory.

    writeUserConfig({ token: 123 }, ".zoorc");
    const conf = readUserConfig(".zoorc");
  7. Configure RCOptions

    main

    When using read, write, update, or parse, you can pass an RCOptions object to control behavior:

    • name (string, optional): The name of the configuration file (e.g., .myconfig). Defaults to .conf.
    • dir (string, optional): The directory where the file is located or should be written. Defaults to process.cwd().
    • flat (boolean, optional): If true, the parser will not unflatten nested keys into objects; it will return a flat object where keys include dot notation (e.g., {'a.b': 1}). Defaults to false.
  8. Reference: RC9 Public API and Types

    main

    Functions

    FunctionDescription
    parse(contents: string, options?: RCOptions): RCParses a string of config content.
    parseFile(path: string, options?: RCOptions): RCParses a config file at the given path.
    read(options?: RCOptions | string): RCReads the configuration.
    readUserConfig(options?: RCOptions | string): RCReads config from the user's config directory.
    userConfigDir(): stringReturns the user's config directory path.
    serialize(config: RC): stringConverts a config object to a string.
    write(config: RC, options?: RCOptions | string): voidWrites the configuration.
    writeUserConfig(config: RC, options?: RCOptions | string): voidWrites config to the user's config directory.
    update(config: RC, options?: RCOptions | string): RCUpdates the configuration.
    updateUserConfig(config: RC, options?: RCOptions | string): RCUpdates user configuration.

    Types

    type RC = Record<string, any>;
    
    interface RCOptions {
      name?: string; // Name of the config file
      dir?: string;   // Directory to look in
      flat?: boolean; // Disable unflattening if true
    }

    Default Options

    {
      "name": ".conf",
      "dir": "process.cwd()",
      "flat": false
    }
  9. Deprecated: `readUser`, `writeUser`, and `updateUser`

    main

    The functions readUser, writeUser, and updateUser are deprecated. They use process.env.XDG_CONFIG_HOME || homedir() but do not follow strict XDG conventions as reliably as the *UserConfig counterparts.

    Recommendation: Use readUserConfig, writeUserConfig, and updateUserConfig instead.

  10. Write configuration files with `write()` and `serialize()`

    main

    The write() function serializes a JavaScript object into a key=value string format and saves it to a file. The serialize() function performs only the string conversion without writing to disk.

    import { write, serialize } from 'rc9';
    
    const config = { foo: 'bar', nested: { a: 1 } };
    
    // Write to file
    write(config, { name: '.settings', dir: './data' });
    
    // Get string representation
    const str = serialize(config);
    // "foo=bar\nnested.a=1"
  11. Parse configuration strings with `parse()`

    main

    The parse function converts a raw configuration string (formatted as key=value pairs) into a JavaScript object. It supports nested objects via dot notation and arrays using the [] suffix on keys. By default, it unflattens the object, but you can keep it flat by setting flat: true in the options.

    import { parse } from 'rc9';
    
    const contents = 'foo=bar\nnested.key=value\nlist[]=item1\nlist[]=item2';
    const config = parse(contents);
    // Result: { foo: 'bar', nested: { key: 'value' }, list: ['item1', 'item2'] }
  12. Update configuration files with `update()`

    main

    The update() function merges a new configuration object with the existing file contents and writes the result back to disk. It uses defu for merging, meaning the provided object takes precedence over the existing file content.

    import { update } from 'rc9';
    
    // Merges { newKey: 'newValue' } into the existing file
    const updatedConfig = update({ newKey: 'newValue' }, { name: '.conf' });