KV.JS Documentation

repository·main·Indexed 23 days ago

https://github.com/heyputer/kv.js

A fast, modern, in-memory key-value store for JavaScript inspired by Redis and Memcached. It provides a lightweight alternative for caching with support for strings, lists, sets, sorted sets, hashes, and geospatial indexes. Features include over 140 functions, atomic increments/decrements, TTL management, glob-style pattern matching, and optional IndexedDB persistence for browser environments.

Tokens
5.2K
Snippets
5
Records
26
Agent score
31%

What's inside @heyputer/kv.js

  1. Overview of KV.JS capabilities

    main

    KV.JS is a fast, pure JavaScript in-memory data store designed as a lightweight alternative to Redis when running a full Redis instance is overkill. It supports a wide variety of data types and operations, including:

    • Data Types: Strings, lists, sets, sorted sets, hashes, and geospatial indexes.
    • Operations: Over 140 functions including SET, GET, EXPIRE, DEL, INCR, DECR, LPUSH, RPUSH, SADD, SREM, HSET, HGET, and more.
  2. Basic usage of KV.JS

    main

    KV.JS is an in-memory data store inspired by Redis and Memcached. You can create an instance, set values, retrieve them, delete them, and set expiration times on keys.

    const kvjs = require('@heyputer/kv.js');
    
    // Create a new kv.js instance
    const kv = new kvjs();
    
    // Set a key
    kv.set('foo', 'bar');
    
    // Get the key's value
    kv.get('foo'); // "bar"
    
    // Delete the key
    kv.del('foo');
    
    // Set another key
    kv.set('username', 'heyputer');
    
    // Automatically delete the key after 60 seconds
    kv.expire('username', 60);
  3. Initialize the kvjs client

    main

    To use kvjs, instantiate the kvjs class. You can pass a string as the argument to set the dbName, or pass an options object for more control.

    If you are running in a browser environment and provide a dbName, the client will automatically attempt to initialize IndexedDB for persistent storage. If you need to ensure IndexedDB is ready before performing operations, call await client.waitForInitialization().

  4. Manage key expiration and TTL

    main

    Control how long keys remain valid using expire, expireat, or persist.

    • expire(key, seconds, [options]): Sets a TTL in seconds. Options include NX (only if no expiry exists), XX (only if expiry exists), GT (only if new TTL > current), and LT (only if new TTL < current).
    • expireat(key, timestamp, [options]): Sets a TTL to a specific Unix timestamp.
    • persist(key): Removes the expiration from a key.
    • ttl(key): Returns the remaining time-to-live in seconds.
    // Set a key's time to live in seconds
    kv.expire('username', 60);
    
    // Set the TTL for key "user1" to expire in 30 seconds
    kv.expireat("user1", Math.floor(Date.now() / 1000) + 30);
    
    // Remove the expiration from the key "key1"
    kv.persist("key1");
    
    // Check the time-to-live of key 'username'
    kv.ttl('username');
  5. Work with Sets

    main

    KV.JS provides Set operations to manage collections of unique members.

    • sadd(key, ...members): Adds one or more members to a set.
    • smembers(key): Retrieves all members of a set.
    • sismember(key, member): Checks if a value is in a set.
    • scard(key): Returns the number of members in a set.
    • spop(key, [count]): Removes and returns random members.
    • smove(source, destination, member): Moves a member from one set to another.
    • Set Math:
      • sinter(key1, key2, ...): Intersection (members in all sets).
      • sdiff(key1, key2, ...): Difference (members in the first set but not in subsequent sets).
  6. Work with Sorted Sets

    main

    Sorted Sets associate each member with a numeric score, allowing for ordered retrieval.

    • zadd(key, score, member, ...): Adds or updates members with scores.
    • zcard(key): Returns the number of members.
    • zcount(key, min, max): Returns the number of members with scores within a range.
    • zrange(key, min, max): Returns members within a score range.
    • zrangebyscore(key, min, max): Returns members within a score range.
    • zrank(key, member): Returns the rank of a member.
    • zrem(key, member): Removes a member.
    • zincrby(key, increment, member): Increments a member's score.
  7. Manage key-value pairs with set() and get()

    main

    Use kv.set() to store string values and kv.get() to retrieve them. kv.get() returns null if the key does not exist or has expired. kv.set() supports several powerful options:

    • NX: Only set the key if it does not already exist.
    • XX: Only set the key if it already exists.
    • GET: Returns the existing value while setting the new one.
    • EX: Set an expiration time in seconds.
    • PX: Set an expiration time in milliseconds.
    • EXAT: Set an expiration time at a specific Unix timestamp in seconds.
    • PXAT: Set an expiration time at a specific Unix timestamp in milliseconds.
    • KEEPTTL: Keep the original TTL if the key already exists.
    // Set a basic key-value pair
    kv.set('username', 'john_doe');
    
    // Set a key-value pair only if the key does not already exist (NX option)
    kv.set('username', 'jane_doe', {NX: true});
    
    // Get the existing value and set a new value for a key (GET option)
    kv.set('username', 'mary_smith', {GET: true});
    
    // Set a key-value pair with an expiration time in seconds (EX option)
    kv.set('session_token', 'abc123', {EX: 3600});
    
    // Get the value of an existing key
    kv.get('username');
  8. Batch operations and pattern matching

    main

    Efficiently manage multiple keys or find keys using patterns.

    • mget(key1, key2, ...): Retrieves values for multiple keys.
    • mset(key1, val1, key2, val2, ...): Sets multiple key-value pairs.
    • del(key1, key2, ...): Deletes specified keys. Returns the number of keys deleted.
    • exists(key1, key2, ...): Checks existence of multiple keys. Returns the count of existing, non-expired keys.
    • keys(pattern): Finds all keys matching a glob-style pattern (e.g., user:*).
    • getset(key, new_value): Replaces the value and returns the old value.
  9. Perform atomic increments and decrements

    main

    Use incr and decr for simple unit changes, or incrby and decrby to change values by a specific amount. These operations work on numeric values. If a key does not exist, incr and incrby treat the initial value as 0.

    // Increment the value of an existing key by 1
    kv.incr("key1");
    
    // Increment the value of a key by 5
    kv.incrby('counter', 5);
    
    // Decrement the value of the key by 1
    kv.decr('counter');
    
    // Decrement the value of the key by 5
    kv.decrby('counter', 5);
  10. Manage Sorted Sets with Z-commands

    main

    Sorted sets are collections of unique members, each associated with a score. Use these methods to manipulate and query them:

    Score Manipulation

    • zincrby(key, increment, member): Increments the score of a member by a given value. Returns the new score.
    • zscore(key, member): Retrieves the score of a specific member.

    Range and Rank Queries

    • zrange(key, start, stop): Returns members and scores within a rank range (supports negative indices for counting from the end).
    • zrevrange(key, start, stop): Returns members and scores in reverse rank order.
    • zrangebyscore(key, min, max, options): Returns members within a score range. Use options.withscores: true to include scores, and options.limit: { offset, count } for pagination.
    • zrangebylex(key, min, max, options): Returns members within a lexicographical range. Supports options.limit.
    • zrank(key, member): Returns the zero-based rank of a member.
    • zrevrank(key, member): Returns the rank of a member when scores are ordered high to low.

    Set Operations

    • zinter(...keys): Returns a Set of members present in all specified sorted sets.
    • zinterstore(destination, ...keys): Computes the intersection of multiple sorted sets and stores the result (using the maximum score of the intersecting members) in destination.
    • zunion(keys): Returns an array of members and their combined scores from the union of the sets.
    • zunionstore(destination, keys): Computes the union and stores it in destination.

    Popping Members

    • zpopmax(key, count): Removes and returns the count members with the highest scores.
    • zpopmin(key, count): Removes and returns the count members with the lowest scores.
    • zmpop(count, ...keys): Pops the lowest-scoring members from the first non-empty set among the provided keys.
  11. Rename a key with rename()

    main
    The rename(key, newKey) method changes the name of an existing key. If the key does not exist, it throws an error: ERR no such key. If the key and newKey are identical, it returns true. The method preserves any expiration time associated with the original key.