Skip to content

Instantly share code, notes, and snippets.

@steriley
Last active May 10, 2019 17:31
Show Gist options
  • Save steriley/4e5046eea465ac5031f4148ffb94fddd to your computer and use it in GitHub Desktop.
Save steriley/4e5046eea465ac5031f4148ffb94fddd to your computer and use it in GitHub Desktop.
promise-ftp with multi-file upload
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
@JNBourrat
Copy link

Hey @steriley, thanks for the public gist, it really helped me a lot!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment