Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

zookeeper

yfinkelstein27.5kMIT6.2.3TypeScript support: included

apache zookeeper client (zookeeper async API v3.5.x - v3.8.x)

apache, zookeeper, client, typescript

readme

node-zookeeper

Overview

node-zookeeper - A Node.js client for Apache Zookeeper.

This node module is implemented on top of the official ZooKeeper C Client API, supporting ZooKeeper server v3.5.x - v3.8.x. Have a look at the official docs for further details on behavior.

Latest changes are described in the changelog

Installation

npm install zookeeper

And you're done!

(note the name zookeeper in lowercase)

Examples

const ZooKeeper = require('zookeeper');

The ZooKeeper client support both callbacks and Promises using the then or async/await syntax.

Documentation

The source code is documented with JSDoc code comments and TypeScript type declarations.

Also, have a look at the API documentation here:

Example: create a client

Create an instance of the ZooKeeper client:

function createClient(timeoutMs = 5000) {
    const config = {
        connect: host,
        timeout: timeoutMs,
        debug_level: ZooKeeper.constants.ZOO_LOG_LEVEL_WARN,
        host_order_deterministic: false,
    };

    return new ZooKeeper(config);
}

const client = createClient();

The client is ready when connected to a ZooKeeper server:

client.on('connect', () => {
    // start using the client
});

client.init(config);

Example: create a node

Using the API:

const path = '/myPath';
try {
    const createdPath = await client.create(path, data, ZooKeeper.constants.ZOO_EPHEMERAL);

    console.log(`(created: ${createdPath})`);
} catch (error) {
    console.log(`${path} already exists`);
}

More examples

Have a look at the code in the examples folder: with master, workers, tasks and listeners scenarios.

API Reference

Methods: async/await enabled client methods

:green_circle: New since 5.2.1: :red_circle: the async functions will reject, when the underlying client returns an error code. This is a bug fix. Before this, errors were failing silently.

  • init(options)
  • connect(options, connect_cb)
  • close()
  • path = await create(path, data, flags, ttl)
  • mkdirp(path, callback(Error))
  • stat = await exists(path, watch)
    • rejects if node does not exist. There's also a pathExists as an alternative.
  • trueOrFalseValue = await pathExists(path, watch)
  • [stat, string|Buffer] = await get(path, watch)
  • children = await get_children(path, watch)
  • [children, stat] = await get_children2( path, watch)
    • return value types:
      • children is an array of strings
      • stat is an object
  • stat = await set(path, data, version)
  • val = await sync(path)
  • delete_ (path, version)
    • (note the trailing _)
  • config = getconfig(watch)
  • reconfig(joining, leaving, members, config_version)
  • set_acl(path, version, acl)
  • acl = await get_acl(path)
  • add_auth(scheme, auth)

The watcher methods are forward-looking subscriptions that can recieve multiple callbacks whenever a matching event occurs.

  • stat = await w_exists(path, watch_cb)
    • rejects if node does not exist. There's also a w_pathExists as an alternative.
  • trueOrFalseValue = await w_pathExists(path, watch)
  • [stat, string|Buffer] = await w_get(path, watch_cb)
  • children = await w_get_children(path, watch_cb)
  • [children, stat] = await w_get_children2 (path, watch_cb)
    • return value types:
      • children is an array of strings
      • stat is an object
  • config = w_getconfig(watch_cb)

Methods: callbacks based client methods

  • init(options)
  • connect(options, connect_cb)
  • close()
  • a_create(path, data, flags, path_cb)
  • a_createTtl(path, data, flags, ttl, pathCb)
  • mkdirp(path, callback(Error))
  • a_exists(path, watch, stat_cb)
  • a_get(path, watch, data_cb)
  • a_get_children(path, watch, child_cb)
  • a_get_children2(path, watch, child2_cb)
  • a_set(path, data, version, stat_cb)
  • a_sync(path, value_cb)
  • a_delete_ (path, version, void_cb)
    • (note the trailing _)
  • a_getconfig(watch, data_cb)
  • a_reconfig(joining, leaving, members, version, data_cb)
  • a_set_acl(path, version, acl, void_cb)
  • a_get_acl(path, acl_cb)
  • add_auth(scheme, auth, void_cb)

The watcher methods are forward-looking subscriptions that can recieve multiple callbacks whenever a matching event occurs.

  • aw_exists(path, watch_cb, stat_cb)
  • aw_get(path, watch_cb, data_cb)
  • aw_get_children(path, watch_cb, child_cb)
  • aw_get_children2(path, watch_cb, child2_cb)
  • aw_getconfig(watch_cb, data_cb)

Callback Signatures

  • path_cb : function(rc, error, path)
  • stat_cb : function(rc, error, stat)
    • Invoked with error set if path does not exist, also for a_exists() calls
  • data_cb : function(rc, error, stat, data)
  • child_cb : function(rc, error, children)
  • child2_cb : function(rc, error, children, stat)
  • value_cb : function(rc, error, value)
  • void_cb : function(rc, error)
  • watch_cb : function(type, state, path)
  • acl_cb : function(rc, error, acl, stat)
  • connect_cb: function(err, zookeeper)

Input Parameters

  • options : object. valid keys: { connect, timeout, debug_level, host_order_deterministic, data_as_buffer, response_counter_limit }
  • path : string
  • data : string or Buffer
  • flags : int32. Supported:
    • ZOO_PERSISTENT
    • ZOO_EPHEMERAL
    • ZOO_PERSISTENT_SEQUENTIAL
    • ZOO_EPHEMERAL_SEQUENTIAL
    • ZOO_CONTAINER
    • ZOO_PERSISTENT_WITH_TTL
    • ZOO_PERSISTENT_SEQUENTIAL_WITH_TTL
  • version : int32. null or undefined will skip version checking.
  • watch : boolean
  • ttl: int32. TTL in milliseconds. Must be positive if any of the TTL modes is used; otherwise undefined.
  • scheme : authorisation scheme (digest, auth)
  • joining : string. Comma separated list of servers to be added. null for non-incremental reconfiguration.
  • leaving : string. Comma separated list of servers to be removed. null for non-incremental reconfiguration.
  • members : string. Comma separated list of new membership. null for incremental reconfiguration.
  • config_version : int64. -1 to skip version checking
  • auth : authorisation credentials (username:password)
  • acl : acls list (same as output parameter, look below) - read only

Output Parameters

  • path is a string
  • data is either a Buffer (default), or a string (this is controlled by data_as_buffer = true/false)
  • children is an array of strings
  • rc is an int (error codes from zk api)
  • error is a string (error string from zk api)
  • type is an int event type (from zk api)
  • state is an int (state when the watcher fired from zk api)
  • stat is an object with the following attributes:
    • long czxid // created zxid
    • long mzxid // last modified zxid
    • long ctime // created
    • long mtime // last modified
    • int version // version
    • int cversion // child version
    • int aversion // acl version
    • string ephemeralOwner // owner session id if ephemeral, 0 otw
    • int dataLength // length of the data in the node
    • int numChildren // number of children of this node
    • long pzxid // last modified children
  • acl is an array of acls objects, single acl object has following key
    • int perm // permisions
    • string scheme // authorisation scheme (digest, auth)
    • string auth // authorisation credentials (username:hashed_password)
  • zookeeper is the ZooKeeper instance on which connect was called

Session state machine is well described in the Zookeeper docs

ACL and authorisation

The library comes with 3 default ACL levels defined (comes from ZK):

  • ZooKeeper.constants.ZOO_OPEN_ACL_UNSAFE - anyone can do anything
  • ZooKeeper.constants.ZOO_READ_ACL_UNSAFE - anyone can read
  • ZooKeeper.constants.ZOO_CREATOR_ALL_ACL - gives full rights to authorised user (you have to be authorised first, otherwise it will result with "invalid acl")

If you don't want to use predefined ACLs you can define your own (the ACL object is described above), for limiting permisions you can use:

  • ZooKeeper.constants.ZOO_PERM_READ - read permission
  • ZooKeeper.constants.ZOO_PERM_WRITE - write permission
  • ZooKeeper.constants.ZOO_PERM_CREATE - create permission
  • ZooKeeper.constants.ZOO_PERM_DELETE - delete permission
  • ZooKeeper.constants.ZOO_PERM_ADMIN - admin permission
  • ZooKeeper.constants.ZOO_PERM_ALL - all of the above

For more details please refer to ZooKeeper docs.

Windows support

Windows 10 is supported out of the box with no additional requirements other than Node.js itself.

Running a different Windows version? Install CMake to build a ZooKeeper client on Windows and install Python.

Also, run npm install in a Powershell window. For further instructions visit node-gyp documentation.

Windows support has been enabled mainly for supporting development, not for production.

Development

To run full output during the module build one has to use ZK_INSTALL_VERBOSE flag.

ZK_INSTALL_VERBOSE=1 npm install

For Windows (PowerShell): verbose build

$env:ZK_INSTALL_VERBOSE=1
npm install

This PowerShell command will remove the environment variable:

Remove-Item Env:\ZK_INSTALL_VERBOSE

Implementation Notes

  • Zookeeper C API library comes in 2 flavours: single-threaded and multi-threaded. For node.js, single-threaded library provides the most sense since all events coming from ZooKeeper responses have to be dispatched to the main JavaScript thread.
  • The C++ code uses the same logging facility that ZK C API uses internally. Hence zk_log.h file checked into this project. The file is considered ZooKeeper internal and is not installed into /usr/local/include
  • Multiple simultaneous ZooKeeper connections are supported and tested
  • All ZooKeeper constants are exposed as read-only properties of the ZooKeeper function, like ZK.ZOO_EPHEMERAL
  • All ZooKeeper API methods including watchers are supported.

Known Bugs & Issues

  • The lib will segfault if you try to use a ZooKeeper intance after the on_closed event is delivered (possibly as a result of session timeout etc.) YOU MAY NOT re-use the closed ZooKeeper instance. You should allocate a new one and initialize it as a completely new client. Any and all watchers from your first instance are lost, though they may fire (before the on_close) see below.
  • Any established watches may/will be fired once each when/if your client is expired by the ZooKeeper server, the input arguments are observed to be: type=-1, state=1, path="". Care should be taken to handle this differently than a "real" watch event if that matters to your application.

Contribute to the project

Check out the issues tab and grab one! Read the contributing document.

See Also

Acknowledgments

  • Apache ZooKeeper ™ source code is included in this repository. An open source volunteer project under the Apache Software Foundation.

LICENSE

See LICENSE-MIT.txt file in the top level folder.

ORIGINAL AUTHOR

Yuri Finkelstein (yurif2003 at yahoo dot com)

with awesome contributions from:

  • Woody Anderson (Woodya)
  • Dave Dopson (ddopson)
  • Ryan Phillips (rphillips)
  • David Trejo (DTrejo)
  • Mark Cavage (mcavage)
  • Jakub Lekstan (kuebk)
  • Matt Lavin (mdlavin)
  • David Vujic (davidvujic)
  • Jakub Bieńkowski (jbienkowski311)
  • Brendan Hack (bhack-onshape)

changelog

v 6.2.3 (2024-07-14)

  • fix: accept both perm and perms in acl objects

    Pull request 349 by @maharjanraj

v 6.2.2 (2024-07-08)

  • docs: access Zookeeper constants from ZooKeeper.constants

    Pull request 347 by @maharjanraj

v 6.2.1 (2024-07-04)

  • fix: ACL type, should be an array of objects. Also, fix typo in permissions key.

    Pull request 346 by @davidvujic

v 6.2.0 (2024-05-25)

  • fix: build error in Node.js 22 caused by removed V8 AccessControl property

    Pull request 344 by @davidvujic

v 6.1.1 (2024-01-28)

  • fix: return an invalid state error code (previously segfault) when client not properly initialized.

    Pull request 338 by @davidvujic

v 6.1.0 (2023-12-26)

  • feat: Add prebuilds for Node.js v.20 for Mac OS X x86 and arm, Windows.

    Pull requests: 333 334 335 by @davidvujic

v 6.0.0 (2023-08-07)

  • feat: use ZooKeeper C Client v3.8.2 and add prebuilds for Node.js v.18 (Mac OS X intel and M1, and Windows)

    Drop support for Node.js 16 prebuilds.

    Pull request 330 by @davidvujic

v 5.6.0 (2022-11-03)

  • feat: add prebuilds for Node.js v.18 (Mac OS X intel and M1, and Windows)

    Pull request 324 by @davidvujic

v 5.5.1 (2022-09-17)

  • fix: set the correct supported version of Apache ZooKeeper server (docs and package description). Pull request 322 by @davidvujic

v 5.5.0 (2022-09-17)

  • fix: Remove the OpenSSSL FIPS_mode check for Linux, Mac OS X and Windows.

    feat: Rebuild the prebuilds for Mac OS X and Windows, using Node.js 16.17.0.

    feat: Remove the prebuilds for Node.js 14.

    Pull request 321 by @davidvujic

  • fix: remove code using FIPS_mode which is not available on all distros. Pull request 318 by @dreusel

v 5.4.0 (2022-04-18)

  • feat: starting the zookeeper client in a Node.js Worker thread. Pull request 310 by @deepcoldy

v 5.3.2 (2022-02-16)

  • fix: handle normalize path with slashes in all platforms. Pull request 305 by @hufeng

v 5.3.1 (2022-02-12)

  • fix: get and w_get returns an array of [stat, string|Buffer]. Pull request 306 by @davidvujic

v 5.3.0 (2022-01-09)

  • feat: Add Mac OS X M1 prebuild for Node.js 16.13.1. Pull request 302 by @davidvujic
  • fix: node-gyp is already included in npm. Pull request 301 by @davidvujic
  • fix: replace lodash with vanilla js, remove unused dependencies, remove unnecessary usage of t.plan() in Ava tests.

    NOTE:

    the _.defaults lodash function is replaced with Object.assign (with src and target flipped) to have a similar behaviour as the lodash function.

    But it isn't 100% the same thing. If the original object has a key with an undefined value, it will behave differently than with the lodash defaults fn.

    Pull request 300 by @davidvujic

v 5.2.2 (2022-01-08)

  • fix(testing): replace the existing integration test scripts (that has become an unwanted and rarely used legacy), with new ones using the Ava test tool. Pull request 297 by @davidvujic
  • fix(testing): Use Ava v4. Pull request 296 by @davidvujic
  • fix: Bump dependencies, remove unused integration test, remove unused dependencies. Pull request 295 by @davidvujic

v 5.2.1 (2022-01-05)

  • fix: explicitly handle async JavaScript failures. Pull request 293 by @davidvujic

v 5.2.0 (2022-01-05)

  • feat: add a boolean "path exists" function, wrapping the "exists" function. Pull request 291 by @davidvujic

v 5.1.0 (2021-12-29)

  • feat: build native addon from the ZooKeeper C client v3.6.3. Pull request 289 by @davidvujic
  • fix: Using a newer client solves issue 270 (warnings on close).
  • feat: Using the client with v3.6.2 enables SSL support for Linux, as described in the pull request 289
  • dev: using CircleCI instead of TravisCI. Pull request 288 by @davidvujic
  • breaking change: removed custom addon build for the solaris OS. This has not been tested for years and most likely not working.

v 5.0.0 (2021-12-06)

  • feat: add Node.js 16 prebuilds for Windows. Pull request 284 by @miroslavpokorny
  • feat: add Node.js 16 prebuilds for Mac OS X (x64 arch), and drop support for Node.js 12. Pull request 285 by @davidvujic

v 4.10.1 (2021-11-08)

  • fix: replace the tape unit test library with ava. Pull request 282 by @davidvujic

v 4.10.0 (2021-06-09)

  • feat: ability to overwrite default response counter limit. Pull request 278 by @wareczek

v 4.9.0 (2021-05-13)

  • feat: Dynamic Reconfiguration. Pull request 273 by @bhack-onshape

v 4.8.2 (2021-04-20)

  • fix: set initial value to noResponseCounter on init and reset on close. Pull request 271 by @davidvujic

v 4.8.1 (2021-02-18)

  • fix: the watch param passed in to the exists (the promise based) function is a boolean. Pull request 266 by @davidvujic
  • chore: Node.js LTS 12 and 14 is enough for running in a CI. Pull request 267 by @davidvujic

v 4.8.0 (2021-01-31)

  • feat: add support for TTL and Container nodes. Pull request 255 by @dreusel
  • fix: Example code: use one client, use only when connected Pull request 264 by @davidvujic

v 4.7.1 (2020-12-27)

  • fix: build an AddOn from the ZooKeeper C Client v3.5.8 in all platforms (Linux, Mac OS X and Windows). Pull request 260 by @davidvujic

v 4.7.0 (2020-12-17)

  • feat: include prebuilt binaries for Mac OS X (darwin, x64) and Windows - for node 12 and 14. This will simplify and fasten the install process a lot. Pull request 251 by @davidvujic
  • fix: note about rejecting/erroring when path does not exist in exists() calls. Pull request 256 by @dreusel
  • docs: simplify docs and add info about prebuilds. Pull request 253 by @davidvujic

v 4.7.0-beta.0 (2020-11-29)

  • feat: include prebuilt binaries for Mac OS X (darwin, x64) and Windows - for node 12 and 14. This will simplify and fasten the install process a lot. Pull request 252 by @davidvujic

v 4.6.0 (2020-10-31)

  • feat: The default API from the library is the async/await enabled client (containing both callbacks and promisified methods)
  • fix: add TypeScript declarations. Pull request 246 by @davidvujic

v 4.5.3 (2020-09-20)

  • fix: Update depencencies causing warnings on install. Pull request 242 by @davidvujic

v 4.5.2 (2020-01-22)

  • fix: try an alternative shasum command when missing on Linux systems. Pull request 234 by @hwzhangd

v 4.5.1 (2019-12-09)

  • fix: add_auth expecting three arguments, add the missing voidCb parameter. Pull request 230 by @wareczek

v 4.5.0 (2019-11-05)

  • feat: Zookeeper 3.5.6. Pull request 226
  • fix: Rollback for Windows client (3.4.14). This is the motivation for bumping the Minor version. Pull request 226

v 4.4.2 (2019-09-21)

  • fix: too many close events emitted from the client caused by ZNOTHING socket responses. Pull request 221
  • fix: remove duplicate parameter definitions

v 4.4.1 (2019-08-22)

  • fix: include ZooKeeper source code, instead of downloading on install, pull request 219
  • feat: Integration tests in Docker, pull request 218 by @jbienkowski
  • feat: less verbose Windows builds, pull request 217
  • fix: GCC build errors, pull request 215
  • feat: move constants to a separate file, pull request 212 by @jbienkowski

v 4.4.0 (2019-08-11)

  • fix: typos in the code documentation for async get_children.
  • fix: retry download the ZooKeeper C Client if failed during npm install.
  • feature: use v3.5.5 of the ZooKeeper C Client.

v 4.3.0 (2019-07-30)

  • Refactor all JavaScript code to ECMAScript 2017 and native Promises: pull request 185 by @jbienkowski311
  • Copy instead of symlink in build process (Windows users can install without admin access): pull request 190
  • Quicker build process in Windows, without massive output or warnings: pull request 191
  • Code documentation for public API: pull request 192
  • README revision, simplified and promoting async/await enabled client: pull request 193
  • jsDoc type definitions in code documentation: pull request 196

v 4.2.0 (2019-07-16)

  • fix: Node.js 12 support
  • fix: V8 and Nan deprecation warnings
  • chore: reduce build output on Linux/Mac OS X. Pull request 183 by @jbienkowski311
  • fix: deprecated getters and setters, pull request 181 by @jbienkowski311
  • chore: pull request template, added by @jbienkowski311
  • chore: added integration test scripts

v 4.1.1 (2019-06-18)

  • feat: handle ZNOTHING return code from the ZooKeeper C library
  • fix: README typos
  • chore: added example code in the examples folder - master, workers and tasks
  • chore: run code in a linux docker container using a Dockerfile
  • chore: moved existing manual tests to the tests_integration folder
  • Merge pull request #174 from @peZhmanParsaee: delete .npmignore file
  • Merge pull request #170 from @arpitsingh94: Added documentation for "connect" function
  • Merge pull request #164 from @luc-boussant: Update issue templates
  • Merge pull request #163 from @tabbartley: Add CODE-OF-CONDUCT

v 4.0.3 (2019-04-25)

  • chore: added unit tests, mostly asserting the public API.
  • chore: added ESLint and the Airbnb JavaScript style guide.
  • chore: added .editorconfig

v 4.0.2 (2019-04-13)

v 4.0.1 (2019-03-10)

  • Added docs: changelog, contributing to the project, fixed typos and missing info in the readme file.

v 4.0.0 (2019-03-02)

  • Added Windows support! A long awaited issue finally solved.
  • BREAKING: dropped support for Node.js versions older than version 8.
  • node-zookeeper now uses SemVer for versioning.

Read details about the release here: Windows support

v 3.4.9-4 (2019-01-16)

  • Fixed npm install fails when using Node version 10.

Details about the release here: Node.js 10 support