secret
anonymous / ftp.js
Created

  • Download Gist
ftp.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
/**
* Poor man's FTP client
*
* @param host
* @param port
* @param console
* @constructor
*/
function Ftp(host, port, console) {
this.console = console;
this.host = host;
this.port = parseInt(port);
}
 
/**
* Convert passive response to port number
*
* @param pasv
* @return {Number}
*/
Ftp.pasv2port = function(pasv) {
//227 PASV ok (192,168,1,1,129,178)
var pasvs = pasv.match(/\d+/g); //["227", "192", "168", "1", "1", "129", "178"]
var port = parseInt(pasvs[6]) + 256 * parseInt(pasvs[5]); //33202
return port;
};
 
/**
* Download a file
*
* @param path
* @param callback
*/
Ftp.prototype.retrieve = function(path, eofHandler) {
var self = this;
var controlSocket, binarySocket; //commands usually 21, transfers usually > 1023
//callback hell
this.console && console.log('[Ftp]', 'retrieve', path);
controlSocket = new Socket(function() {
controlSocket.connect(self.host, self.port, function() {
controlSocket.read(function(data) {
controlSocket.write('PASV\r\n', function() {
controlSocket.read(function(pasv) {
binarySocket = new Socket(function() {
binarySocket.connect(self.host, Ftp.pasv2port(pasv), function() {
controlSocket.write('RETR ' + path + '\r\n');
binarySocket.stream(eofHandler);
});
}, self.console);
});
});
});
});
}, self.console);
};
 
/**
* Delete a file
*
* @param path
* @param callback
*/
Ftp.prototype.deleteFile = function(path, callback) {
var self = this;
var controlSocket, binarySocket;
this.console && console.log('[Ftp]', 'delete', path);
controlSocket = new Socket(function() {
controlSocket.connect(self.host, self.port, function() {
controlSocket.read(function(data) {
controlSocket.write('DELE ' + path + '\r\n', function() {
controlSocket.read(function(operation) {
//console.log(operation);
callback && callback();
});
});
});
});
}, self.console);
};
 
/**
* Remove a directory
*
* @param path
* @param callback
*/
Ftp.prototype.removeDirectory = function(path, callback) {
var self = this;
var controlSocket, binarySocket;
this.console && console.log('[Ftp]', 'removeDirectory', path);
controlSocket = new Socket(function() {
controlSocket.connect(self.host, self.port, function() {
controlSocket.read(function(data) {
controlSocket.write('RMD ' + path + '\r\n', function() {
controlSocket.read(function(operation) {
//console.log(operation);
callback && callback();
});
});
});
});
}, self.console);
};

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.