Skip to content

Instantly share code, notes, and snippets.

@mplewis
Last active August 29, 2015 14:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mplewis/4779c1ab1ae2394cfef7 to your computer and use it in GitHub Desktop.
Save mplewis/4779c1ab1ae2394cfef7 to your computer and use it in GitHub Desktop.
var fs = require('fs');
var path = require('path');
var glob = require('glob');
var async = require('async');
var Client = require('./client').Client;
var client = new Client();
function cp2remote(src, dest, callback) {
client.parse(dest);
var _upload = function(files, callback) {
var rootdir = files[0];
async.eachSeries(files, function(fpath, done) {
fs.stat(fpath, function(err, stats) {
if (err) {
done(err);
return;
}
if (stats.isFile()) {
var fname = path.relative(rootdir, fpath);
client.upload(
fpath, path.join(client.remote.path, fname), done
);
} else {
done();
}
});
}, function(err) {
// never forget to close the session
client.on('close', function() {
callback(err);
});
client.close();
});
};
if (src.indexOf('*') === -1) {
fs.stat(src, function(err, stats) {
if (err) {
callback(err);
return;
}
if (stats.isFile()) {
client.upload(src, client.remote.path, function(err) {
client.on('close', function() {
callback(err);
});
client.close();
});
} else if (stats.isDirectory()) {
glob(src.replace(/\/$/, '') + '/**/**', function(err, files) {
if (err) {
callback(err);
} else {
_upload(files, callback);
}
});
} else {
callback('unsupported');
}
});
} else {
glob(src, function(err, files) {
if (err) {
callback(err);
return;
}
_upload(files, callback);
});
}
}
function cp2local(src, dest, callback) {
var remote = client.parse(src);
// only works on single file now
// TODO: glob match
if (/\/$/.test(dest)) {
dest = dest + path.basename(remote.path);
}
client.download(remote.path, dest, callback);
}
exports = module.exports = client;
exports.scp = function(src, dest, callback) {
client = new Client();
var parsed = client.parse(src);
if (parsed.host && parsed.path) {
cp2local(parsed, dest, callback);
} else {
cp2remote(src, dest, callback);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment