Skip to content

Instantly share code, notes, and snippets.

@petrkohut
Last active July 16, 2021 14:23
Show Gist options
  • Save petrkohut/aad78a80e82b3c922809 to your computer and use it in GitHub Desktop.
Save petrkohut/aad78a80e82b3c922809 to your computer and use it in GitHub Desktop.
Zookeeper + Node.js client examples

Zookeeper in Node.js

Install and run Zookeeper server

Download image

docker pull jplock/zookeeper

Run zookeeper container

docker run -d -p 2181:2181 -p 2888:2888 -p 3888:3888 jplock/zookeeper

MORE INFO: https://registry.hub.docker.com/u/jplock/zookeeper/dockerfile/

Node.js client

var zookeeper = require('node-zookeeper-client');

var client = zookeeper.createClient('localhost:2181');
var path = '/config';

function configChanged(client, path, event, done) {
    console.log('Got event: %s', event);
    getConfig(client, path, done);
}

function getConfig(client, path, done) {
    client.getData(
        path,
        function (event) {
            configChanged(client, path, event, done);
        },
        function (error, data, stat) {
        if (error) {
            return done(error.stack);
        }
        done(null, data.toString('utf8'));
    });
}

client.once('connected', function () {
    console.log('Connected to the server.');
    getConfig(client, path, function (err, data) {
        console.log('Got data: %s', data);
    });
});

client.connect();

Other example functions

function createZnode(client, path) {
    client.create(path, function (error) {
        if (error) {
            console.log('Failed to create node: %s due to: %s.', path, error);
        } else {
            console.log('Node: %s is successfully created.', path);
        }
        client.close();
    });
}

function listChildren(client, path) {
    client.getChildren(
        path,
        function (event) {
            console.log('Got watcher event: %s', event);
            listChildren(client, path);
        },
        function (error, children, stat) {
            if (error) {
                console.log(
                    'Failed to list children of %s due to: %s.',
                    path,
                    error
                );
                return;
            }

            console.log('Children of %s are: %j.', path, children);
        }
    );
}

Links

http://blog.kompany.org/2013/02/23/setting-up-apache-zookeeper-on-os-x-in-five-minutes-or-less/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment