Skip to content

Commit

Permalink
lib/zookeeper.js: add mkdirp
Browse files Browse the repository at this point in the history
  • Loading branch information
DTrejo committed Apr 14, 2012
1 parent 84b0176 commit 9224298
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions lib/zookeeper.js
@@ -1,6 +1,8 @@
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var _ = require('underscore');
var path = require('path');
var async = require('async');

try {
// as of node 0.6.x, node-waf seems to build to a different directory. grr.
Expand Down Expand Up @@ -281,3 +283,54 @@ ZooKeeper.prototype.a_delete_ = function a_delete_() {
return this._native.a_delete_.apply(this._native, arguments);
}

ZooKeeper.prototype.mkdirp = function (p, cb) {
if(this.logger) this.logger("Calling mkdirp with " + util.inspect(arguments));
return mkdirp(this, p, cb);
}

//
// ZK does not support ./file or /dir/../file
// mkdirp(zookeeperConnection, '/a/deep/path/to/a/file', cb)
//
function mkdirp(con, p, callback) {
p = path.normalize(p);
var dirs = p.split('/').slice(1); // remove empty string at the start.

// console.log('dirs', dirs);

var tasks = [];
dirs.forEach(function(dir, i) {
var subpath = '/' + dirs.slice(0, i).join('/') + '/' + dir;
subpath = path.normalize(subpath); // remove extra `/` in first iteration
tasks.push(async.apply(create, con, subpath));
});
async.waterfall(tasks, function(err, results) {
if(err) return callback(err);
// succeeded!
return callback(null, true);
});
}

//
// create(zookeeperConnection, '/some-path', cb)
// if there is a problem:
// cb(error)
// if the dir was created, or already exists:
// cb()
//
function create(con, p, cb) {
var data = 'created by zk-mkdir-p'; // just want a dir, so store something
var flags = 0; // none
con.a_create(p, data, flags, function(rc, error, zkPath) {
// already exists, cool.
// console.log('ZooKeeper.ZNODEEXISTS',ZooKeeper.ZNODEEXISTS);
if(rc == ZooKeeper.ZNODEEXISTS) {
return cb();
}
if(rc != 0) {
return cb(new Error('Zookeeper Error: code='+rc+' '+error));
}
// sucessfully created!
return cb();
});
}

0 comments on commit 9224298

Please sign in to comment.