# memoz

> Memoz is an in-memory database that persists on disk. The data model is key-value.

Latest version **4.2.0** (published 2024-10-21) · 0 weekly downloads

## Install

```sh
npm install memoz
pnpm add memoz
yarn add memoz
bun add memoz
```

## Health

**Score 40/100 (D)** — status: maintenance-mode.

Positive: has types; esm support; no vulnerabilities; high quality score.

Warnings: low downloads.

Negative: stale; low maintenance score.

## Facts

| | |
|---|---|
| Version | 4.2.0 |
| Published | 2024-10-21 |
| First published | 2021-07-26 |
| Weekly downloads | 0 |
| TypeScript types | bundled |
| Module format | ESM + CommonJS |
| Dependencies | 0 |
| Unpacked size | 121.3 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 6 |
| Author | Milad E. Fahmy |
| Maintainers | miladezzat |
| Keywords | data, structure, database, redis, transaction, pipelining, performance, queue, nodejs, pubsub, backpressure, cache, ram, simple, storage, typescript, in-memory, disk, persist, key-value, string, list, set, sorted-set, hash |

## Links

- npm: https://www.npmjs.com/package/memoz
- Repository: https://github.com/miladezzat/memoz
- Homepage: https://memoz.js.org
- Issues: https://github.com/miladezzat/memoz/issues
- npm.io page: https://npm.io/package/memoz

## Alternatives

- [memory-cache](https://npm.io/package/memory-cache.md) — 795.0K weekly downloads
- [@httptoolkit/proxy-agent](https://npm.io/package/@httptoolkit/proxy-agent.md) — 11.2K weekly downloads
- [express-cache-controller](https://npm.io/package/express-cache-controller.md) — 5.3K weekly downloads
- [http-cache-middleware](https://npm.io/package/http-cache-middleware.md) — 4.5K weekly downloads
- [cache2](https://npm.io/package/cache2.md) — 1.5K weekly downloads

## Recent versions

- 4.2.0 (latest) — 2024-10-21
- 4.1.0 — 2024-10-20
- 4.0.4 — 2024-10-20
- 4.0.3 — 2024-10-20
- 4.0.2 — 2024-10-18
- 4.0.1 — 2024-10-17
- 3.1.0 — 2024-10-08
- 2.2.0 — 2024-09-16
- 2.1.2 — 2022-02-19
- 2.1.1 — 2022-02-11
- 2.1.0 — 2022-02-09
- 2.0.1 — 2021-08-04
- 2.0.0 — 2021-07-31
- 1.1.3 — 2021-07-28
- 1.1.2 — 2021-07-28
- … 3 more at https://npm.io/package/memoz/versions

## README

# Memoz

[![npm version](https://badge.fury.io/js/memoz.svg)](https://badge.fury.io/js/memoz)&nbsp;
![https://img.shields.io/npm/dm/memoz.svg](https://img.shields.io/npm/dm/memoz.svg)

Memoz is an in-memory database that persists on disk, offering easy CRUD operations with a simple API. it supports document persistence to disk.

- [Memoz](#memoz)
  - [Installation](#installation)
  - [Usage](#usage)

## Installation

```bash
npm i memoz
# or
yarn add memoz
```

## Usage

```ts
import { Memoz, FuzzySearchOptions } from "memoz";

interface IUser {
    readonly id?: string;
    name: string;
    age: number;
}

const memoz = new Memoz<IUser>({
    persistToDisk: true,  // to allow persist data on disk - default false
    storagePath: './data', // the location to persist data - default './data'
    useMutex: true, //  Whether to use a mutex for thread safety - default false
});


async function boot() {
    // Uncomment to create and store users in the database
    // const docs = Array.from({ length: 1000 }, (_, i) => ({ name: `User ${i}`, age: i }));
    // await memoz.createMany(docs);

    // Loop to get users with pagination and sorting to test caching
    const totalPages = 2; // Define the total number of pages to iterate over
    const usersPerPage = 10; // Number of users per page

    for (let index = 0; index < totalPages; index++) {
        try {
            const users = await memoz
                .getMany() // Retrieve all users
                .sort([{ name: 'asc' }]) // Sort users by name in ascending order
                .skip(index * usersPerPage) // Calculate the correct offset for pagination
                .limit(usersPerPage); // Limit the number of users retrieved

            console.log(`Page ${index + 1}:`, users); // Log the users for the current page
        } catch (error) {
            console.error(`Error retrieving users for page ${index + 1}:`, error); // Handle any errors
        }
    }

    // support regex 
      const user = await memoz.getOne({
        field: 'name',
        operator: '$regex',
        value: { $regex: '999', $options: 'i' }, // the $regex can be new RegExp
    });

    console.log(user);


      {
    const options: FuzzySearchOptions = {
      maxDistance: 2,
      scoringStrategy: 'default',
    };

    // Perform a fuzzy search
    const results = await memoz.fuzzySearch('User 999', ['age', 'name'], options, 5);

    console.log(results);
  }

  {
    const options: FuzzySearchOptions = {
      maxDistance: 2,
      scoringStrategy: 'tokenCount',
      fieldWeights: { title: 2, content: 1 }, // Title matches count more
    };

    // Perform a fuzzy search
    const results = await memoz.fuzzySearch('User 999', ['age', 'name'], options);
    console.log(results.slice(0, 2));
  }
  {
    const customScoringFn = (token: string, fieldToken: string, distance: number, fieldWeight: number) => {
      const baseScore = fieldWeight * (1 / (distance + 1)); // Decrease score as distance increases
      const titleBonus = fieldToken.includes(token) ? 1 : 0; // Bonus if the fieldToken contains the token
      return baseScore + titleBonus; // Total score
    };

    // Example usage
    const options: FuzzySearchOptions = {
      maxDistance: 2,
      scoringStrategy: 'custom',
      customScoringFn,
    };

    // Perform a fuzzy search
    const results = await memoz.fuzzySearch('User 999', ['age', 'name'], options);
    console.log(results.slice(0, 2));
  }
}

// Start the boot process
boot();
```

---
_Source: https://npm.io/package/memoz · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
