Created
May 23, 2019 12:51
-
-
Save acecconato/c71b11b0e25066b10c41036ad1a37311 to your computer and use it in GitHub Desktop.
npm ftp + npm util-promisifyall: Read directory and subfolders recursively
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
/** | |
* Install dependencies with npm: | |
* npm i ftp | |
* npm i util-promisifyall | |
*/ | |
const promisifyAll = require('util-promisifyall'); | |
const Client = require('ftp'); | |
/** | |
* CONFIGURE YOUR OWN FTP ! | |
*/ | |
const config = { | |
host: process.env.FTP_HOST, | |
port: process.env.FTP_PORT || 21, | |
user: process.env.FTP_USER, | |
password: process.env.FTP_PASSWORD, | |
}; | |
let client = new Client(); | |
client = promisifyAll(client); | |
client.autoConnect = async () => { | |
await client.connect(config); | |
return new Promise(resolve => { | |
client.on('ready', _ => resolve()); | |
}); | |
}; | |
client.recursiveList = async (path) => { | |
if (!this.filelist) | |
this.filelist = []; | |
const rootList = await client.listAsync(path); | |
const promises = await rootList.map(file => { | |
return new Promise((resolve) => { | |
let filePath = `${path}/${file.name}`; | |
if (file.type === 'd') { | |
resolve(client.recursiveList(filePath)); | |
} else { | |
file.parentDir = filePath.replace(file.name, ''); | |
file.path = filePath; | |
this.filelist.push(file); | |
resolve(); | |
} | |
}); | |
}); | |
await Promise.all(promises); | |
return this.filelist; | |
}; | |
module.exports = client; |
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
const client = require('./client'); | |
// Call with async await | |
(async () => { | |
await client.autoConnect(); | |
const remoteFiles = await client.recursiveList('/home'); | |
remoteFiles.forEach(file => console.log(file.path)); | |
})(); | |
// Or call with .then() | |
(() => { | |
client.autoConnect().then(_ => { | |
client.recursiveList('/home').then(remoteFiles => { | |
remoteFiles.forEach(file => console.log(file.path)); | |
}); | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment