Skip to content

Instantly share code, notes, and snippets.

@beaspider
Created December 7, 2012 17:22
Show Gist options
  • Save beaspider/4234826 to your computer and use it in GitHub Desktop.
Save beaspider/4234826 to your computer and use it in GitHub Desktop.
SFTP utils
/**
* Get the SFTP binary based on OS
*/
var binary = function() {
var windows = require("os").type().match(/windows/i);
return windows ? "psftp" : "sftp";
}
/**
* Utility function to process SFTP commands
* Callback function on completion gets 4 params: exit_code,exit_signal,infos, errors
* e.g. function(exit_code,exit_signal,infos,errors)
* The exit_code and exit_signal are the standard params returned from the node.js exit event
* (a successful exit has a code of 0)
* The infos and errors are just strings containing any info and error logs from the SFTP commands
* @param server
* @param user
* @param password
* @param commands
* @param callback
*/
exports.processCommands = function processCommands(server,user,password,commands,callback) {
var buffer_infos = '';
var buffer_errors = '';
var shell;
shell = require("child_process").spawn(_binary(),[server,"-l",user,"-pw",password,"-v"]);
commands.forEach( function(command) {
buffer_infos += 'INFO: ' + "Executing command: " + command;
shell.stdin.write(command + "\n");
shell.stdin.end();
});
shell.stdout.on('data', function (data) {
buffer_infos += 'INFO: ' + data;
});
shell.stderr.on('data', function (data) {
buffer_errors += 'WARN: ' + data;
});
shell.on('exit', function(code, signal) {
callback(code,signal,buffer_infos,buffer_errors)
});
}
/**
* Utility function to return stats for the specified filename
* currently just returns file size
* @param server
* @param user
* @param password
* @param filename
* @param dir
*/
exports.filestats = function(server,user,password,filename,dir) {
var commands = [];
if (dir) {
commands.push("cd " + dir);
}
commands.push("dir");
commands.push("exit");
processCommands(server,user,password,commands,function(exit_code,exit_signal,infos,errors) {
// get file size
var buffer = infos.substring(0,infos.indexOf(filename));
// then find 4 spaces - this is just before the size in the output
var index = buffer.lastIndexOf(' ') + 4;
buffer = buffer.substring(index);
// find next single space this is just after the size
buffer = buffer.substring(0,buffer.indexOf(' '));
return {
size: buffer
};
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment