npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

tfa-jsonmap

v1.3.0

Published

⚡ A simple, powerful, and useful database based on JSON files

Downloads

8

Readme

⚡ A simple, powerful, and useful JSON database, similar to Map but with over 50+ methods and features, and the data is saved in a specific .json file.

  • Beginner-Friendly.
  • Simple, free, and easy to use.
  • Helpful guide by using IntelliSense and in declaration files.
  • Built-in Math conditions (including strict mode).
  • Customizable only allowed types for property values.
  • 100% written in TypeScript.

Note: It is recommended to use TypeScript for the types. You can use JavaScript but it will not care about the types, which is going to cause many errors and problems in the future.

Table of Contents

Requirements

  • Node.js version 16.0.0 or above.

Installation

Install the latest version:

npm install tfa-jsonmap

Install the latest prerelease version:

npm install tfa-jsonmap@prerelease

What's new?

  • New methods: setJSON, lock, and unlock.
  • New property: locked (boolean).

Load a module

TypeScript:

import { } from 'tfa-jsonmap';

JavaScript (CommonJS):

const { } = require('tfa-jsonmap');

↑ Back to top

Example usage

Define a new database using JSONMap:

import { JSONMap } from 'tfa-jsonmap';

const db = new JSONMap<any>('./path/to/your/json/file.json');

↑ Back to top

Type parameter using interface keyword:

interface User {
    name: string,
    age: number,
    gender?: 'Male' | 'Female', // <= Optional property
    hobbies: string[]
};

const db = new JSONMap<User>('./path/to/your/json/file.json');

db.set('Micheal', {
    name: 'Micheal',
    age: 45,
    hobbies: ['Football', 'Tennis']
});

↑ Back to top

Using simple methods:

const db = new JSONMap<string|number|string[]>('./path/to/your/json/file.json');

db.set('username', 'T.F.A');
db.set('balance', 69420);
db.set('langs', ['PY', 'TS']);

db.push('langs', 'Rust', 'JS'); // => langs: ['PY', 'TS', 'Rust', 'JS']
db.filter('langs', (item) => item !== 'Rust'); // => langs: ['PY', 'TS', 'JS']

db.has('balance'); // => true
db.delete('balance');
db.has('balance'); // => false

db.keys(); // => ['username', 'langs']
db.values(); // => ['T.F.A', ['PY', 'TS, 'JS']]

db.reverse();

db.keys(); // => ['langs', 'username']
db.values(); // => [['PY', 'TS, 'JS'], 'T.F.A']

db.keyIndex('langs'); // => 0
db.keyAt(1); // => 'username'

db.hasAll('username', 'langs'); // => true
db.hasAll('username', 'age', 'langs'); // => false

db.hasAny('username', 'langs'); // => true
db.hasAny('username', 'age', 'langs'); // => true

db.deleteMany('username', 'langs');

db.keys(); // => []

db.set('var1', 45);
db.set('var2', 45);
db.set('var3', '45');
db.set('var4', 60);

db.on('keyCreate', (key, value) => { });
db.on('keyDelete', (key) => { });

db.$equalTo('var1', 'var2'); // => true
db.$equalTo('var2', 'var3'); // => true
db.$strictEqualTo('var2', 'var3'); // => Error: TypeError

db.$lessThan('var4', 'var2'); // => false
db.$greaterThan('var4', 'var2'); // => true

db.$lessThanOrEqual('var1', 'var2'); // => true
db.$greaterThanOrEqual('var2', 'var4'); // => false

db.typeofKey('var3'); // => string
db.typeofKey('var1'); // => number

db.isRepeated(45); // => true
db.isRepeated(60); // => false

db.replace('var2', 'var4'); // => var4: 45

db.deleteMany('var2', 'var4');

db.map((K, V) => `K: ${K}; V: ${V}`); // => ['K: var1; V: 45', 'K: var3; V: 45']

db.clone<any>('new-file.json')
    .then((newdb) => newdb.toJSON()); // => { 'var1': 45, 'var3': '45' }

db.toJSON(); // => { 'var1': 45, 'var3': '45' }

↑ Back to top

Constructor options

| Option | Type | Required? | Default | Description | | ------ | ----- | ----- | ----- | ----- | | autoclear | boolean | No | false | Clear the data on startup? || prettier | boolean | No |false` | Make the JSON file looks pretty? |

↑ Back to top

Type parameter

This only works for TypeScript. The types below are for keys' values. By default, it's any. This is also applies for the method JSONMap#clone().

new JSONMap<string>(); // Only string is acceptable.
new JSONMap<number>(); // Only number is acceptable. 
new JSONMap<boolean>(); // Only boolean is acceptable.
new JSONMap<object>(); // Only object is acceptable.
new JSONMap<[]>(); // Only array is acceptable.
new JSONMap<null>(); // Only null is acceptable. 
new JSONMap<any>();// Any type is acceptable.

↑ Back to top

Modules

Class: JSONMap

  • Methods: [55]
    • $equalTo: Whenever the first key's value is equal to second key's value.
    • $greaterThan: First key > Second key
    • $greaterThanOrEqual: First key >= Second key
    • $lessThan: First key < Second key
    • $lessThanOrEqual: First key <= Second key
    • $strictEqualTo: Whenever the first key's value is equal to second key's value, and must have same type value.
    • at: Get an element from a key's value array by it's index.
    • clear: Delete all the keys.
    • clone: Create a new JSON file with the same data as the original one.
    • delete: Delete a key.
    • deleteMany: Delete multiple keys.
    • emit: Event method; Emit a custom event or built-in event.
    • entries: Get all the entries; keys and their value.
    • fill: Replace all values with a new value.
    • filter: Filter an array, it's mostly used to pull multiple elements from an array.
    • firstKey: Get the first key's name from the data.
    • firstValue: Get the first value from the data.
    • forEach: Similar to for keyword. First argument is the key, second argument is the value.
    • get: Get a key's value.
    • getMany: Get multiple keys' values in an array.
    • has: Whenever the provided key exists in the data or not.
    • hasAll: Whenever all the provided keys exists in the data. If one of them doesn't, even the others exist, it will return false.
    • hasAny: Whenever all the provided keys exists in the data. If one of them exist, even the others doesn't exist, it will return true.
    • isNull: Whenever the provided key is having the null value or not.
    • isRepeated: Whenever the provided value exists in two or more different key names.
    • keyAt: Get a key's name by it's index from the data.
    • keyIndex: Get a key's index by it's name from the data.
    • keys: Get all the keys in an array.
    • lastKey: Get the last key's name from the data.
    • lastValue: Get the last value from the data.
    • lock: Lock the map, which means that you can't overwrite the data.
    • map: Similar to array map method. First argument is key name, second argument is key's value, third argument is the index.
    • on: Event method; Emits whenever something has happened. Events: keyCreate, keyDelete.
    • once: Event method; Emits whenever something has happened and then stops. Events: keyCreate, keyDelete.
    • off: Event method; Removes a listener from an event.
    • pop: Pull the last element from an array.
    • push: Push multiple elements in an array. If the original key's value is not an array, it will do nothing.
    • randomKey: Random key name that exist in the data.
    • randomValue: Random value name that exist in the data.
    • removeAllListeners: Event method; Removes all the listeners.
    • replace: Replace a key's value by another key's value.
    • reverse: Reverse all the entries.
    • set: Add a new key and it's value in the data.
    • setJSON: Overwrites the file with new data (Dangerous method).
    • shift: Pull the first element from an array.
    • sortKeys: Sort keys array, similar to array sort method.
    • sortValues: Sort values array, similar to array sort method.
    • toJSON: Returns the file data.
    • typeofKey: Type of key's value.
    • unlock: Unlock the map, which means that you can overwrite the data again.
    • unshift: Push multiple values in the first index of an array.
    • values: Get all the values in an array.
    • (private) write: Overwrites the file with new data.
    • (private) read: Returns the file data.
  • Properties: [4]
    • locked: Whenever the map is locked or not.
    • size: Get the total keys saved in the data.
    • (read-only) path: Get the path of the JSON file.
    • (read-only) (private) prettier: Whenever the option prettier is enabled or disabled.

↑ Back to top

Enum: Events

  • KeyCreate: Whenever a new key has added into the data. First argument: key (string), second argument: value (any).
  • KeyDelete: Whenever a key has been deleted from the data. First argument: key (string)

↑ Back to top

FAQs

I am getting a SyntaxError, what should I do?

If your error is same as "SyntaxError: Unexpected end of JSON input", add a new empty object into the JSON file. The file content should look like this (instead of an empty file):

{}

Unfortunately, there is no auto-fix for this problem. :(

↑ Back to top

What is prettier in the constructor options?

It will make the JSON file looks pretty and easily readable.

Toggle enabled: (true)

{
    "username": "T.F.A",
    "langs": [
        "JS",
        "TS",
        "PY",
        "Bash"
    ]
}

Toggle disabled: (false)

{"username":"T.F.A","langs":["JS","TS","PY","Bash"]}

↑ Back to top

How to pull an element from an array?

Use the method filter, it will filter the array and saves the new filtered array.

Pull some specific elements:

// Pull a string:
db.filter((item) => item !== 'string');

// Pull a number:
db.filter((item) => item !== 69420);

// Pull a boolean:
db.filter((item) => item !== false);

// Pull an object:
db.filter((item) => item['property'] !== 'value');

// Pull multiple elements (any type) at same time:
db.filter((item) => item !== 'something' && item !== true);

Pull everything except specific elements:

Same example as above, but the condition must be equal (===) instead of not equal (!==).

↑ Back to top

License

The MIT License

Copyright (c) 2023 T.F.A

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

↑ Back to top

This project is under the license of MIT. Copyright (©) 2023 T.F.A