etcd3 API - v2.0.0
    Preparing search index...

    Class Election

    Implementation of elections, as seen in etcd's Go client. Elections are most commonly used if you need a single server in charge of a certain task; you run an election on every server where your program is running, and among them they will choose one "leader".

    There are two main entrypoints: campaigning via Election.campaign, and observing the leader via Election.observe.

    import * as os from 'node:os';
    const client = new Etcd3();
    const election = client.election('singleton-job');

    function runCampaign() {
    const campaign = election.campaign(os.hostname())
    campaign.on('elected', () => {
    // This server is now the leader! Let's start doing work
    doSomeWork();
    });
    campaign.on('error', error => {
    // An error happened that caused our campaign to fail. If we were the
    // leader, make sure to stop doing work (another server is the leader
    // now) and create a new campaign.
    console.error(error);
    stopDoingWork();
    setTimeout(runCampaign, 5000);
    });
    }

    async function observeLeader() {
    const observer = await election.observe();
    console.log('The current leader is', observer.leader());
    observer.on('change', leader => console.log('The new leader is', leader));
    observer.on('error', () => {
    // Something happened that fatally interrupted observation.
    setTimeout(observeLeader, 5000);
    });
    }
    Index
    name: string
    prefix: "election" = 'election'

    Prefix used in the namespace for election-based operations.

    • Puts the value as eligible for election. Multiple sessions can participate in the election, but only one can be the leader at a time.

      A common pattern in cluster-based applications is to campaign the hostname or IP of the current server, and allow the leader server to be elected among them.

      You should listen to the error and elected events on the returned object to know when the instance becomes the leader, and when its campaign fails. Once you're finished, you can use Campaign.resign to forfeit its bid at leadership.

      Once acquired, instance will not lose its leadership unless resign() is called, or error is emitted.

      Parameters

      • value: string

      Returns Campaign

    • Returns the currently-elected leader value (passed to campaign() or proclaim()), or undefined if there's no elected leader.

      Parameters

      • Optionalencoding: BufferEncoding

      Returns Promise<string | undefined>

    • Returns the currently-elected leader value (passed to campaign() or proclaim()), or undefined if there's no elected leader.

      Parameters

      • encoding: "buffer"

      Returns Promise<Buffer<ArrayBufferLike> | undefined>

    • Creates an observer for the election, which emits events when results change. The observer must be closed using observer.cancel() when you're finished with it.

      Returns Promise<ElectionObserver>