Introduction to Enmap
Enmap (Enhanced Map) is an open-source key-value database for Node.js designed to be easy to use yet powerful. It allows developers to use a simple map-like API to interact with persistent data storage, making it a great choice for applications that require fast and efficient database operations.
Getting Started
To install Enmap, you can use npm:
npm install enmap
To initialize Enmap:
const Enmap = require('enmap'); const myEnmap = new Enmap({ name: 'mydatabase' });
Setting and Getting Data
Setting a value in Enmap is as simple as using the set
method.
myEnmap.set('key', 'value');
To retrieve the value:
console.log(myEnmap.get('key')); // Output: 'value'
Deleting Data
You can easily delete a key-value pair with the delete
method:
myEnmap.delete('key');
Checking Existence
To check if a key exists, use the has
method:
console.log(myEnmap.has('key')); // Output: false
Incrementing and Decrementing
Enmap allows you to increment or decrement values directly:
myEnmap.set('counter', 1); myEnmap.inc('counter'); console.log(myEnmap.get('counter')); // Output: 2 myEnmap.dec('counter'); console.log(myEnmap.get('counter')); // Output: 1
Fetching All Entries
You can fetch all entries in the Enmap with:
myEnmap.fetchEverything().forEach((value, key) => { console.log(key, value); });
Filtering Data
Filter data stored in Enmap using the filter
method:
const filterResults = myEnmap.filter((value, key) => value.startsWith('a'));
Enmap in a Real Application
Below is an example of how you might use Enmap in a simple application to store user data:
const Enmap = require('enmap'); const userData = new Enmap({ name: 'userData' });
// Adding user data userData.set('user1', { name: 'Alice', age: 25 }); userData.set('user2', { name: 'Bob', age: 30 });
// Retrieving user data console.log(userData.get('user1')); // Output: { name: 'Alice', age: 25 }
// Checking user existence console.log(userData.has('user2')); // Output: true
// Updating user data userData.set('user1.age', 26);
// Deleting user data userData.delete('user2');
In this example, user data is stored and managed efficiently using the Enmap API.
Hash: 1dad6f7cf2c97cedc185e0986819134b98311e8633b338f1889109ed2ca52407