Permalink
Browse files

add recursive option to mkdir()

this algorithm assumes a server that uses '/' as a path separator
  • Loading branch information...
1 parent b5111e9 commit 1f32e8ec1cf4d8818a90371e733f530d199dad09 @mscdex committed Dec 18, 2012
Showing with 65 additions and 2 deletions.
  1. +65 −2 lib/ftp.js
View
@@ -594,8 +594,71 @@ FTP.prototype.cdup = function(cb) { // CDUP is optional
});
};
-FTP.prototype.mkdir = function(path, cb) { // MKD is optional
- this._send('MKD ' + path, cb);
+FTP.prototype.mkdir = function(path, recursive, cb) { // MKD is optional
+ if (typeof recursive === 'function') {
+ cb = recursive;
+ recursive = false;
+ }
+ if (!recursive)
+ this._send('MKD ' + path, cb);
+ else {
+ var self = this, owd, abs, dirs, dirslen, i = -1, searching = true;
+
+ abs = (path[0] === '/');
+ if (path.indexOf('/') === -1)
+ this._send('MKD ' + path, cb);
+ else {
+ function nextDir() {
+ if (++i === dirslen) {
+ // return to original working directory
+ return self._send('CWD ' + owd, cb, true);
+ }
+ if (searching) {
+ self._send('CWD ' + dirs[i], function(err, text, code) {
+ if (code === 550) {
+ searching = false;
+ --i;
+ } else if (err) {
+ // return to original working directory
+ return self._send('CWD ' + owd, function() {
+ cb(err);
+ }, true);
+ }
+ nextDir();
+ }, true);
+ } else {
+ self._send('MKD ' + dirs[i], function(err, text, code) {
+ if (err) {
+ // return to original working directory
+ return self._send('CWD ' + owd, function() {
+ cb(err);
+ }, true);
+ }
+ self._send('CWD ' + dirs[i], nextDir, true);
+ }, true);
+ }
+ }
+ this.pwd(function(err, cwd) {
+ if (err)
+ return cb(err);
+ owd = cwd;
+ if (abs)
+ path = path.substr(1);
+ if (path[path.length - 1] === '/')
+ path = path.substring(0, path.length - 1);
+ dirs = path.split('/');
+ dirslen = dirs.length;
+ if (abs)
+ self._send('CWD /', function(err) {
+ if (err)
+ return cb(err);
+ nextDir();
+ }, true);
+ else
+ nextDir();
+ });
+ }
+ }
};
FTP.prototype.rmdir = function(path, cb) { // RMD is optional

0 comments on commit 1f32e8e

Please sign in to comment.