CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-node-persist

Super-easy (and fast) persistent data structures in Node.js, modeled after HTML5 localStorage

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

initialization.mddocs/

Initialization and Configuration

Essential setup methods for configuring node-persist storage behavior, directory paths, serialization options, TTL defaults, and performance settings.

Capabilities

Async Initialization

Initializes the default storage instance asynchronously, creating the storage directory if needed.

/**
 * Initializes the default storage instance asynchronously
 * @param options - Configuration options for storage behavior
 * @returns Promise resolving to the applied options
 */
async function init(options?: StorageOptions): Promise<StorageOptions>;

Usage Examples:

const storage = require('node-persist');

// Basic initialization with default options
await storage.init();

// Initialize with custom directory
await storage.init({
  dir: './my-storage',
  logging: true
});

// Initialize with TTL and custom serialization
await storage.init({
  dir: '/tmp/cache',
  ttl: 24 * 60 * 60 * 1000, // 24 hours
  stringify: JSON.stringify,
  parse: JSON.parse,
  encoding: 'utf8'
});

Synchronous Initialization

Initializes the default storage instance synchronously, creating the storage directory if needed.

/**
 * Initializes the default storage instance synchronously
 * @param options - Configuration options for storage behavior
 * @returns The applied options object
 */
function initSync(options?: StorageOptions): StorageOptions;

Usage Examples:

const storage = require('node-persist');

// Synchronous initialization
storage.initSync({
  dir: './sync-storage',
  ttl: 60000 // 1 minute TTL
});

// Can immediately use storage methods after initSync
await storage.setItem('key', 'value');

Storage Instance Factory

Creates a new LocalStorage instance with optional configuration (useful for multiple storage locations).

/**
 * Creates a new LocalStorage instance with optional configuration
 * @param options - Configuration options for the new instance
 * @returns New LocalStorage instance (must still call init)
 */
function create(options?: StorageOptions): LocalStorage;

Usage Examples:

const storage = require('node-persist');

// Create separate storage instances
const userStorage = storage.create({ dir: './users' });
const sessionStorage = storage.create({ dir: './sessions', ttl: 3600000 });

// Initialize each instance
await userStorage.init();
await sessionStorage.init();

// Use independently
await userStorage.setItem('user1', { name: 'Alice' });
await sessionStorage.setItem('session1', 'abc123');

Configuration Options

Complete configuration interface with all available options and their defaults.

interface StorageOptions {
  /** Storage directory path (relative or absolute) */
  dir?: string; // default: '.node-persist/storage'
  
  /** Function to serialize objects to strings */
  stringify?: (obj: any) => string; // default: JSON.stringify
  
  /** Function to parse strings back to objects */
  parse?: (str: string) => any; // default: JSON.parse
  
  /** File encoding for storage files */
  encoding?: string; // default: 'utf8'
  
  /** Enable logging (boolean) or provide custom logging function */
  logging?: boolean | Function; // default: false
  
  /** Default TTL in milliseconds, or true for 24h default */
  ttl?: number | boolean; // default: false
  
  /** Interval for automatic expired item cleanup (milliseconds) */
  expiredInterval?: number; // default: 120000 (2 minutes)
  
  /** Ignore corrupted storage files instead of throwing errors */
  forgiveParseErrors?: boolean; // default: false
  
  /** Use write queue for better performance and consistency */
  writeQueue?: boolean; // default: true
  
  /** How often to process write queue (milliseconds) */
  writeQueueIntervalMs?: number; // default: 1000
  
  /** Only write the last value when multiple writes to same key */
  writeQueueWriteOnlyLast?: boolean; // default: true
  
  /** Limit concurrent file descriptors to avoid EMFILE errors */
  maxFileDescriptors?: number; // default: Infinity
}

Common Configuration Patterns:

// High-performance caching setup
await storage.init({
  dir: '/tmp/app-cache',
  ttl: 3600000, // 1 hour
  writeQueue: true,
  writeQueueWriteOnlyLast: true,
  maxFileDescriptors: 256,
  expiredInterval: 300000 // 5 minutes
});

// Development/debugging setup
await storage.init({
  dir: './dev-storage',
  logging: true,
  forgiveParseErrors: true,
  writeQueue: false // immediate writes for debugging
});

// Production setup with custom serialization
await storage.init({
  dir: process.env.STORAGE_DIR || './production-storage',
  ttl: false, // no default TTL
  expiredInterval: 600000, // 10 minutes
  maxFileDescriptors: 512,
  stringify: (obj) => JSON.stringify(obj, null, 0),
  parse: JSON.parse,
  logging: (msg) => console.log(`[storage] ${msg}`)
});

Storage Directory Management

The storage directory is automatically created if it doesn't exist. Directory paths can be relative (to current working directory) or absolute.

Directory Path Resolution:

  • Relative paths: resolved relative to process.cwd()
  • Absolute paths: used as-is
  • Default: .node-persist/storage (relative to current working directory)

Important Notes:

  • The storage directory should only contain files created by node-persist
  • Setting forgiveParseErrors: true allows the presence of non-storage files
  • Each storage instance should use a separate directory to avoid conflicts

docs

index.md

initialization.md

low-level-operations.md

query-operations.md

storage-operations.md

tile.json