Skip to content

Instantly share code, notes, and snippets.

@acecconato
Created May 23, 2019 12:51
Show Gist options
  • Save acecconato/c71b11b0e25066b10c41036ad1a37311 to your computer and use it in GitHub Desktop.
Save acecconato/c71b11b0e25066b10c41036ad1a37311 to your computer and use it in GitHub Desktop.
npm ftp + npm util-promisifyall: Read directory and subfolders recursively
/**
* 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;
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