getter.js 1.32 KB
'usu strict';

import _ from 'lodash';
import zookeeper from 'node-zookeeper-client';

import creator from './creator';

const getter = (server, client, path, resolve, reject) => {
    client.exists(path, (err, stat) => {
        if (err) {
            console.log('path %s exits error', path, err.stack);
            resolve(false);
            return;
        }

        if (stat) {
            client.getData(
                path,
                (err, data, stat) => {
                    if (err) {
                        console.log('Got path %s data error', path, err.stack);
                    }
                    client.close();

                    resolve((data && data.toString('utf8') === 'true') ? true : false);
                }
            )
        } else {
            // 不存在的路径
            console.log('no path %s, we will create it with value "false" automatic', path);
            client.close();

            // create path
            creator(server, path);

            resolve(false);
        }
    });
    
};

module.exports = (server, path) => new Promise((resolve, reject) => {
    const client = zookeeper.createClient(server);

    client.once('connected', () => {
        getter(server, client, path, resolve, reject);
    });

    client.connect();
});