Last active
May 10, 2019 17:31
-
-
Save steriley/4e5046eea465ac5031f4148ffb94fddd to your computer and use it in GitHub Desktop.
promise-ftp with multi-file upload
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var promisify = require('promisify-node'), | |
PromiseFtp = require('promise-ftp'), | |
fs = promisify('fs') | |
var _ftp = new PromiseFtp(), | |
_localFilePath = './data/', | |
_remoteFilePath = '/public_html/temp/' | |
function Ftp(env){ | |
this.config = { | |
host: 'host', | |
user: 'user', | |
password: 'password' | |
} | |
} | |
Ftp.prototype.mput = function(fileList){ | |
_ftp.connect(this.config) | |
.then(() => multiPutFiles(fileList)) | |
.then(() => { | |
// clear cache here | |
console.log('disconnecting...') | |
return _ftp.end() | |
}) | |
// connection errors | |
.catch((err) => { console.log(err.toString()) }) | |
} | |
Ftp.prototype.publish = function(ext){ | |
return fs.readdir(_localFilePath) | |
.then(function(files){ | |
var pattern = new RegExp('.' + ext) | |
return files.filter((file) => pattern.test(file)) | |
}) | |
} | |
function multiPutFiles(fileList){ | |
return new Promise(function(resolve, reject){ | |
var chain = Promise.resolve() | |
fileList.forEach(function(file, i, arr){ | |
chain = chain.then(() => { | |
console.log('uploading:', _localFilePath + file) | |
return _ftp.put(_localFilePath + file, _remoteFilePath + file) | |
}) | |
// file upload errors | |
.catch((err) => { console.log(err.toString()) }) | |
if(i === arr.length - 1) | |
chain.then(() => resolve()) | |
}) | |
}) | |
} | |
//var ftp = new Ftp('LIVE'); | |
//ftp.publish('json').done((files) => ftp.mput(files)) | |
//ftp.mput(['test.txt', 'test1.txt']) | |
module.exports = Ftp |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey @steriley, thanks for the public gist, it really helped me a lot!