Get Hazelcast

Hazelcast Node.js Client

Node JS

Hazelcast IMDG enables you to accelerate your Node.js applications and work with native Javascript objects or JSON. You can:

  • Build a multi-layer cache for your applications with Hazelcast Map, a distributed & replicated key-value store.
  • Query JSON data at speeds far surpassing traditional document stores.
  • Use the Hazelcast Near Cache feature to store frequently read data in your Node.js process. This provides faster read speeds than popular caching solutions.
  • Enable pub-sub communication between application instances.
  • Deal with high load for view or like events by using a conflict-free replicated counter.
  • Prevent races when accessing 3rd-party services by using Lock and other distributed concurrency primitives available in Hazelcast CP Subsystem, powered by the Raft consensus algorithm.
Quick Start + Download

Quick Start + Download

Quick Start

Available on NPM: npmjs.com/package/hazelcast-client

npm install hazelcast-client --save

Version Downloads Documentation
Hazelcast IMDG NodeJS Client 5.0.2 (latest)
10/15/2021
Hazelcast IMDG NodeJS Client 5.0.1
10/05/2021
Hazelcast IMDG NodeJS Client 5.0.0
10/01/2021
Hazelcast IMDG NodeJS Client 4.2.0
06/04/2021

For all downloads please see the Download Archives

Previous Releases
Code Samples

Code Samples

Map Replicated Map Multimap Set List Queue ReliableTopic Query Lock
Enable Code Wrap
'use strict';

const { Client } = require('hazelcast-client');

(async () => {
    try {
        // Start the Hazelcast Client and connect to an already running
        // Hazelcast Cluster on 127.0.0.1
        const hz = await Client.newHazelcastClient();
        // Get the Distributed Map from Cluster
        const map = await hz.getMap('my-distributed-map');
        // Standard Put and Get
        await map.put('key', 'value');
        await map.get('key');
        // Concurrent Map methods, optimistic updating
        await map.putIfAbsent('somekey', 'somevalue');
        await map.replace('key', 'value', 'newvalue');
        // Shutdown this Hazelcast client
        await hz.shutdown();
    } catch (err) {
        console.error('Error occurred:', err);
    }
})();
Get this code sample on Github
'use strict';

const { Client } = require('hazelcast-client');

(async () => {
    try {
        // Start the Hazelcast Client and connect to an already running
        // Hazelcast Cluster on 127.0.0.1
        const hz = await Client.newHazelcastClient();
        // Get a Replicated Map called 'my-replicated-map'
        const map = await hz.getReplicatedMap('my-replicated-map');
        // Put and Get a value from the Replicated Map
        // (key/value is replicated to all members)
        const replacedValue = await map.put('key', 'value');
        // Will print 'Replaced value: null' as it's the first update
        console.log('Replaced value:', replacedValue);
        const value = await map.get('key');
        // The value is retrieved from a random member in the cluster
        console.log('Value for key:', value);
        // Shutdown this Hazelcast client
        await hz.shutdown();
    } catch (err) {
        console.error('Error occurred:', err);
    }
})();
Get this code sample on Github
'use strict';

const { Client } = require('hazelcast-client');

(async () => {
    try {
        // Start the Hazelcast Client and connect to an already running
        // Hazelcast Cluster on 127.0.0.1
        const hz = await Client.newHazelcastClient();
        // Get the Distributed MultiMap from Cluster
        const multiMap = await hz.getMultiMap('my-distributed-multimap');
        // Put values in the map against the same key
        await multiMap.put('my-key', 'value1');
        await multiMap.put('my-key', 'value2');
        await multiMap.put('my-key', 'value3');
        // Print out all the values for associated with key called 'my-key'
        const values = await multiMap.get('my-key');
        for (const value of values) {
            console.log(value);
        }
        // remove specific key/value pair
        await multiMap.remove('my-key', 'value2');
        // Shutdown this Hazelcast client
        await hz.shutdown();
    } catch (err) {
        console.error('Error occurred:', err);
    }
})();
Get this code sample on Github
'use strict';

const { Client } = require('hazelcast-client');

(async () => {
    try {
        // Start the Hazelcast Client and connect to an already running
        // Hazelcast Cluster on 127.0.0.1
        const hz = await Client.newHazelcastClient();
        // Get the Distributed Set from Cluster
        const set = await hz.getSet('my-distributed-set');
        // Add items to the set with duplicates
        await set.add('item1');
        await set.add('item1');
        await set.add('item2');
        await set.add('item2');
        await set.add('item2');
        await set.add('item3');
        // Get the items. Note that there are no duplicates
        const items = await set.toArray();
        console.log(items);
        // Shutdown this Hazelcast client
        await hz.shutdown();
    } catch (err) {
        console.error('Error occurred:', err);
    }
})();
Get this code sample on Github
'use strict';

const { Client } = require('hazelcast-client');

(async () => {
    try {
        // Start the Hazelcast Client and connect to an already running
        // Hazelcast Cluster on 127.0.0.1
        const hz = await Client.newHazelcastClient();
        // Get the Distributed List from Cluster
        const list = await hz.getList('my-distributed-list');
        // Add elements to the list
        await list.add('item1');
        await list.add('item2');
        //Remove the first element
        const value = await list.removeAt(0);
        console.log('Removed:', value);
        // There is only one element left
        const len = await list.size();
        console.log('Current size is', len);
        // Clear the list
        await list.clear();
        // Shutdown this Hazelcast client
        await hz.shutdown();
    } catch (err) {
        console.error('Error occurred:', err);
    }
})();
Get this code sample on Github
'use strict';

const { Client } = require('hazelcast-client');

(async () => {
    try {
        // Start the Hazelcast Client and connect to an already running
        // Hazelcast Cluster on 127.0.0.1
        const hz = await Client.newHazelcastClient();
        // Get a Queue called 'my-distributed-queue'
        const queue  = await hz.getQueue('my-distributed-queue');
        // Offer a string into the Distributed Queue
        await queue.offer('item');
        // Poll the Distributed Queue and return the string
        await queue.poll();
        // Timed-restricted operations
        await queue.offer('anotheritem', 500);
        await queue.poll(5000);
        // Indefinitely-waiting operations
        await queue.put('yetanotheritem');
        const item = await await queue.take();
        console.log(item);
        // Shutdown this Hazelcast Client
        await hz.shutdown();
    } catch (err) {
        console.error('Error occurred:', err);
    }
})();
Get this code sample on Github
'use strict';

const { Client } = require('hazelcast-client');

(async () => {
    try {
        // Start the Hazelcast Client and connect to an already running
        // Hazelcast Cluster on 127.0.0.1
        const hz = await Client.newHazelcastClient();
        // Get a Topic called 'my-distributed-topic'
        const topic = await hz.getReliableTopic('my-distributed-topic');
        // Add a Listener to the Topic
        topic.addMessageListener((message) => {
            console.log(message);
        });
        // Publish a message to the Topic
        await topic.publish('Hello to distributed world');
        // Shutdown this Hazelcast Client
        await hz.shutdown();
    } catch (err) {
        console.error('Error occurred:', err);
    }
})();
Get this code sample on Github
'use strict';

const {
    Client,
    Predicates
} = require('hazelcast-client');

class User {
    constructor(username, age, active) {
        this.username = username;
        this.age = age;
        this.active = active;
        this.factoryId = 1;
        this.classId = 1;
    }

    readPortable(reader) {
        this.username = reader.readUTF('username');
        this.age = reader.readInt('age');
        this.active = reader.readBoolean('active');
    }

    writePortable(writer) {
        writer.writeUTF('username', this.username);
        writer.writeInt('age', this.age);
        writer.writeBoolean('active', this.active);
    }
}

function portableFactory(classId) {
    if (classId === 1) {
        return new User();
    }
    return null;
}

async function generateUsers(usersMap) {
    await usersMap.put('Rod', new User('Rod', 19, true));
    await usersMap.put('Jane', new User('Jane', 20, true));
    await usersMap.put('Freddy', new User('Freddy', 23, true));
}

(async () => {
    try {
        // Start the Hazelcast Client and connect to an already running
        // Hazelcast Cluster on 127.0.0.1
        const hz = await Client.newHazelcastClient({
            serialization: {
                portableFactories: {
                    1: portableFactory
                }
            }
        });
        const usersMap = await hz.getMap('users');
        // Add some users to the Distributed Map
        await generateUsers(usersMap);
        // Create a Predicate from a String (a SQL like Where clause)
        const sqlQuery = Predicates.sql('active AND age BETWEEN (18 AND 21)');
        // Creating the same Predicate as above but with a builder
        const criteriaQuery = Predicates.and(
            Predicates.equal('active', true),
            Predicates.between('age', 18, 21)
        );
        // Get result collections using the two different Predicates
        const result1 = await usersMap.values(sqlQuery);
        const result2 = await usersMap.values(criteriaQuery);
        // Print out the results
        console.log(result1.toArray());
        console.log(result2.toArray());
        // Shutdown this Hazelcast client
        await hz.shutdown();
    } catch (err) {
        console.error('Error occurred:', err);
    }
})();
Get this code sample on Github
'use strict';

const { Client } = require('hazelcast-client');

(async () => {
    try {
        // Start the Hazelcast Client and connect to an already running
        // Hazelcast Cluster on 127.0.0.1
        const hz = await Client.newHazelcastClient();
        // Get the Distributed Lock from CP Subsystem
        const lock = await hz.getCPSubsystem().getLock('my-distributed-lock');
        // Now acquire the lock and execute some guarded code
        const fence = await lock.lock();
        console.log('Fence token:', fence);
        try {
            // Guarded code goes here
        } finally {
            await lock.unlock(fence);
        }
        // Shutdown this Hazelcast client
        await hz.shutdown();
    } catch (err) {
        console.error('Error occurred:', err);
    }
})();
Get this code sample on Github
Roadmap

Roadmap

Upcoming Node.js Client Features

  • Hazelcast Serialization 2.0 Support: Querying friendly and space efficient serialization that has high usability.
  • Sequelize Cache Adaptor: Hazelcast integration to the Sequelize framework, a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite, and Microsoft SQL Server.
  • Integrated Hazelcast caching for your Mongoose queries
  • Express.js Integrations

Recently Released Node.js Client Features

  • SQL Support: Ability to query data stored in Hazelcast Map declaratively.
  • Blue/Green Failover Config: Support of the blue/green deployment and disaster recovery features.
  • External Smart Client Discovery via Load Balancer: Adds a new discovery mechanism that allows smart client to decide whether it needs to use public addresses for communication with members. As a result, Node.js client does not need a dedicated plugin to communicate with a cluster running on a cloud environment where members are exposed via a load balancer.
  • Hazelcast IMDG 4.0 Changes: Client protocol enhancements, architectural improvements, Serialization improvements.
  • Redesign Configuration: Idiomatic configuration.
  • Idiomatic API: Redesign of the API in a way that Node.js developers used to.
  • CP Subsystem Support: New Concurrency APIs including FencedLock, AtomicLong, Semaphore, CountDownLatch, and AtomicReference.
  • Backup Acknowledgment: Significantly improved client performance by eliminating the sync backup wait from the client and send the backup ACK to the client.
  • Ownerless Client: Simpler design to track member leaves and joins to the cluster.
Client Features

Features Implemented for this Client

DATA STRUCTURES

Node.js Client

Map

Queue

Set

List

MultiMap

Replicated Map

Ring Buffer

Topic

Reliable Topic

JCache

N/A

Cardinality Estimator

CONCURRENCY PRIMITIVES

Node.js Client

Lock

Condition

Semaphore

AtomicLong

AtomicReference

ID Generator

CountDownLatch

CRDT PN Counter

Flake ID Generator

DISTRIBUTED PROCESSING

Node.js Client

Distributed Executor Service

Event Listeners

Sub-Listener Interfaces for Map Listener

Entry Processor

TRANSACTIONS

Node.js Client

TxnMap

TxnMultiMap

TxnQueue

TxnList

TxnSet

QUERY

Node.js Client

Query (SQL)

Query (Predicates)

Paging Predicates

Partition Predicates

Built-in Predicates

Continuous Query Caching

N/A

Listener with Predicate

Projections

Fast Aggregations

NEAR CACHE

Node.js Client

Near Cache Support

HD Memory

N/A

Preload Cache from Last Used

Eventual Consistency Control

CONFIGURATION

Node.js Client

Declarative Configuration (XML/JSON/YAML)

JSON

Programmatic Configuration

Client Configuration Import

Fail Fast on Invalid Configuration

SECURITY

Node.js Client

SSL Support

XA Transactions

Mutual Authentication

Authorization

Custom Authentication Modules

MANAGEMENT CENTER

Node.js Client

Management Center Integration / Awareness

Client Near Cache Stats

Client Runtime Stats

Client Operating System Stats

CLOUD

Node.js Client

Hazelcast Cloud

Kubernetes

AWS

Azure

Google Cloud Platform

Pivotal Cloud Foundry

Docker

Apache jclouds

Consul

etcd

Eureka

Heroku

Zookeeper

INFRASTRUCTURE

Node.js Client

Open Client Protocol

Smart Client

Unisocket Client

Lifecycle Service

HeartBeat

Backup Acknowledgement to Client

Diagnostics

SERIALIZATION

Node.js Client

DataSerializable

N/A

IdentifiedDataSerializable

Portable Serialization

Custom Serialization

Global Serialization

CLIENT CONNECTIVITY

Node.js Client

Connection Strategy

Connection Retry

Blue/Green Deployments and Disaster Recovery

Support for Clients & Languages

Jump into the discussion on our groups.