or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

index.mddocs/

Electron Settings

Electron Settings is a simple and robust settings management library for Electron applications. It provides persistent user settings and configuration data storage with atomic file operations, nested object access through key path notation, and both synchronous and asynchronous APIs.

Package Information

  • Package Name: electron-settings
  • Package Type: npm
  • Language: TypeScript
  • Installation: npm install electron-settings
  • Electron Compatibility: Electron >= 2.0.0

Core Imports

import settings from "electron-settings";

For CommonJS:

const settings = require("electron-settings");

Basic Usage

import settings from "electron-settings";

// Set settings with nested objects
await settings.set('color', {
  name: 'cerulean',
  code: {
    rgb: [0, 179, 230],
    hex: '#003BE6'
  }
});

// Get specific nested values using key paths
const colorName = await settings.get('color.name');
// => "cerulean"

const greenValue = await settings.get('color.code.rgb[1]');
// => 179

// Check if key exists
const hasColor = await settings.has('color.name');
// => true

// Get all settings
const allSettings = await settings.get();

// Remove specific setting
await settings.unset('color.name');

Architecture

Electron Settings operates exclusively in the main process and provides:

  • JSON Storage: Settings stored as JSON files in the user data directory
  • Atomic Operations: Uses atomic file writes to prevent data corruption
  • Key Path Navigation: Supports dot notation strings, array paths, and bracket notation
  • Dual APIs: Both async and sync versions of all core functions
  • Configuration: Customizable file location, naming, and formatting options

Capabilities

Settings File Management

Get the path to the settings file and configure library options.

/**
 * Returns the path to the settings file
 * @returns Path to the settings file
 */
function file(): string;

/**
 * Sets configuration options for the library
 * @param customConfig - Configuration options to update
 */
function configure(customConfig: Partial<Config>): void;

/**
 * Resets configuration to defaults
 */
function reset(): void;

interface Config {
  /** Whether to save atomically (default: true) */
  atomicSave: boolean;
  /** Custom settings directory path (default: app user data dir) */
  dir?: string;
  /** Custom Electron instance for testing */
  electron?: typeof Electron;
  /** Settings file name (default: 'settings.json') */
  fileName: string;
  /** JSON formatting spaces when prettify is true (default: 2) */
  numSpaces: number;
  /** Whether to prettify JSON output (default: false) */
  prettify: boolean;
}

Async Settings Operations

Asynchronous functions for reading, writing, and checking settings existence.

/**
 * Checks if a key path exists in settings
 * @param keyPath - Key path to check
 * @returns Promise resolving to boolean indicating existence
 */
function has(keyPath: KeyPath): Promise<boolean>;

/**
 * Gets all settings
 * @returns Promise resolving to complete settings object
 */
function get(): Promise<SettingsObject>;

/**
 * Gets value at specified key path
 * @param keyPath - Key path to retrieve
 * @returns Promise resolving to setting value or undefined
 */
function get(keyPath: KeyPath): Promise<SettingsValue>;

/**
 * Sets all settings to provided object
 * @param obj - New settings object
 * @returns Promise resolving when saved
 */
function set(obj: SettingsObject): Promise<void>;

/**
 * Sets value at specified key path
 * @param keyPath - Key path to set
 * @param value - Value to set
 * @returns Promise resolving when saved
 */
function set(keyPath: KeyPath, value: SettingsValue): Promise<void>;

/**
 * Unsets all settings (clears all)
 * @returns Promise resolving when cleared
 */
function unset(): Promise<void>;

/**
 * Unsets value at specified key path
 * @param keyPath - Key path to unset
 * @returns Promise resolving when saved
 */
function unset(keyPath: KeyPath): Promise<void>;

Sync Settings Operations

Synchronous versions of all core settings operations for immediate execution.

/**
 * Synchronously checks if a key path exists
 * @param keyPath - Key path to check
 * @returns Boolean indicating existence
 */
function hasSync(keyPath: KeyPath): boolean;

/**
 * Synchronously gets all settings
 * @returns Complete settings object
 */
function getSync(): SettingsObject;

/**
 * Synchronously gets value at key path
 * @param keyPath - Key path to retrieve
 * @returns Setting value or undefined
 */
function getSync(keyPath: KeyPath): SettingsValue;

/**
 * Synchronously sets all settings
 * @param obj - New settings object
 */
function setSync(obj: SettingsObject): void;

/**
 * Synchronously sets value at key path
 * @param keyPath - Key path to set
 * @param value - Value to set
 */
function setSync(keyPath: KeyPath, value: SettingsValue): void;

/**
 * Synchronously unsets all settings
 */
function unsetSync(): void;

/**
 * Synchronously unsets value at key path
 * @param keyPath - Key path to unset
 */
function unsetSync(keyPath: KeyPath): void;

Types

/**
 * Key path for accessing nested settings properties
 * Supports dot notation strings, array paths, and bracket notation
 */
type KeyPath = string | Array<string | number>;

/**
 * Valid data types for settings values (JSON-compatible types only)
 * Note: Date objects are not supported - use timestamps or date strings
 */
type SettingsValue = null | boolean | string | number | SettingsObject | SettingsValue[];

/**
 * Object containing settings values as properties
 */
type SettingsObject = {
  [key: string]: SettingsValue;
};

Usage Examples

Configuration and File Management

import settings from "electron-settings";

// Get current settings file path
const filePath = settings.file();
console.log(`Settings stored at: ${filePath}`);

// Configure custom settings
settings.configure({
  fileName: 'app-config.json',
  prettify: true,
  numSpaces: 4
});

// Reset to defaults
settings.reset();

Key Path Navigation

// Using dot notation strings
await settings.set('user.preferences.theme', 'dark');
const theme = await settings.get('user.preferences.theme');

// Using array paths for dynamic keys
const section = 'preferences';
const key = 'theme';
await settings.set(['user', section, key], 'light');

// Using bracket notation for arrays
await settings.set('user.recentFiles', ['file1.txt', 'file2.txt']);
const firstFile = await settings.get('user.recentFiles[0]');

Complex Settings Management

// Set complex nested settings
await settings.set('application', {
  window: {
    width: 1200,
    height: 800,
    maximized: false
  },
  editor: {
    fontSize: 14,
    theme: 'dark',
    features: {
      autoSave: true,
      lineNumbers: true
    }
  },
  recentProjects: [
    { name: 'Project A', path: '/path/to/a' },
    { name: 'Project B', path: '/path/to/b' }
  ]
});

// Check and update specific values
if (await settings.has('application.window.maximized')) {
  await settings.set('application.window.maximized', true);
}

// Get partial settings
const windowSettings = await settings.get('application.window');
const fontSize = await settings.get('application.editor.fontSize');

// Remove specific settings
await settings.unset('application.recentProjects');

Synchronous Operations

// For operations that need immediate results
const hasTheme = settings.hasSync('user.theme');
if (!hasTheme) {
  settings.setSync('user.theme', 'default');
}

const allSettings = settings.getSync();
console.log('Current settings:', allSettings);

Error Handling

try {
  await settings.set('user.preferences', { theme: 'dark' });
} catch (error) {
  console.error('Failed to save settings:', error);
}

// File system errors may occur during read/write operations
// Ensure proper error handling for production applications
try {
  const value = await settings.get('nonexistent.key');
  // Returns undefined for missing keys - no error thrown
} catch (error) {
  // Handles file system errors, JSON parsing errors, etc.
  console.error('Settings error:', error);
}

Important Notes

  • Main Process Only: electron-settings works exclusively in the main process
  • IPC Required: Use IPC communication to access settings from renderer processes
  • JSON Compatibility: Only JSON-compatible values are supported (no Date objects, functions, etc.)
  • Atomic Writes: File operations use atomic writes by default to prevent corruption
  • User Data Directory: Settings stored in Electron's user data directory by default