getter.js 1.34 KB
'usu strict';

const _ = require('lodash');
const zookeeper = require('node-zookeeper-client');

const creator = require('./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();
});