Создайте несколько FTP-клиентов для загрузки файлов с разных серверов соответственно. Это возможно в узле? - PullRequest
0 голосов
/ 20 января 2019

Итак, в моей настройке у меня в сети работает около 7 различных ftp-серверов, и я хочу иметь возможность создавать несколько ftp-клиентов в моем приложении для узла, чтобы получать некоторые файлы с этих серверов соответственно. Мне было интересно, если это вообще возможно или нет? Я смотрю на использование пакета ftp npm: https://www.npmjs.com/package/ftp

Я попробовал пару вещей, таких как следующие, где я создаю несколько экземпляров клиента в массиве, а затем порождаю их, выполняя соединение в конце итерации.

// Create all the clients for each host
// Note that config here is just a JSON object I read at the start
numAddresses = Object.keys(config.addresses).length; //7
clients=[];
for (address in config.addresses) {
    // current address being processed
    console.log(config.addresses[address]);
    // create a new client for this address
    clients[address] = createClient(path);
    // update the settings for this new client based on address
    // note we keep the default anonymous login credential
    // you can change it here though
    connectionSettings.host = config.addresses[address].ip;
    connectionSettings.port = config.addresses[address].port;
    console.log(connectionSettings);
    // connect the current client with the associated settings
    clients[address].connect(connectionSettings);
}

// creates a ftp client and returns it
function createClient(path) {
    var client = new Client();
    // define wait for the server handshake (greeting)
    client.on('greeting', afterGreeting);
    return client;
}
// handles the flow after server handshake (greeting)
function afterGreeting(msg, client) {
    console.log(msg);
    // define wait for the server 'ready' state
    client.on('ready', afterReady);
}
// handles the flow after server 'ready' state
function afterReady() {
    console.log('ready');
    performListing(path);
}
// handles the listing of the files
function performListing(path) {
    console.log('fetching from:'+path);
    client.list(path, performFetch);
}
// handles the fetching of the files
function performFetch(err, list){
    if (err) throw err;
    list.forEach(function (element, index, array) {
        console.log('now copying: '+element.name);
    });
    client.end();
}

Я ожидал, что это просто вызовет все экземпляры этих клиентов в цикле, но я получаю эту ошибку:

D:\node_workspace\ftp\main.js:52
    client.on('ready', afterReady);
TypeError: Cannot read property 'on' of undefined

Я думаю, что сталкиваюсь с какой-то очень простой ошибкой с моими предположениями о том, как работает узел (я новичок). Любая помощь будет оценена.

1 Ответ

0 голосов
/ 20 января 2019

Попробуйте следующий код ...

var Client = require("ftp");

numAddresses = Object.keys(config.addresses).length;

clients = [];
for (address in config.addresses) {
    // current address being processed
    console.log(config.addresses[address]);
    // create a new client for this address
    clients[address] = createClient(path);
    // update the settings for this new client based on address
    // note we keep the default anonymous login credential
    // you can change it here though
    connectionSettings.host = config.addresses[address].ip;
    connectionSettings.port = config.addresses[address].port;
    console.log(connectionSettings);
    // connect the current client with the associated settings
    clients[address].connect(connectionSettings);
}

function createClient(path) {
    var c = new Client();
    c.on('greeting', (msg) => {
        afterGreeting(msg, c);
    });
    return c;
}

function afterGreeting(msg, client) {
    console.log(msg);
    client.on('ready', () => {
        afterReady(client);
    });
}

function afterReady(client) {
    console.log('ready');
    performListing(path, client);
}

function performListing(path, client) {
    console.log('fetching from:' + path);
    client.list(path, (err, list) => {
        performFetch(err, list, client);
    });
}

function performFetch(err, list, client) {
    if (err) throw err;
    list.forEach(function (element, index, array) {
        console.log('now copying: ' + element.name);
    });
    client.end();
}

Обновлено

var Client = require("ftp");

numAddresses = Object.keys(config.addresses).length;

clients = [];
for (address in config.addresses) {
    // current address being processed
    console.log(config.addresses[address]);
    // create a new client for this address
    clients[address] = createClient(path);
    // update the settings for this new client based on address
    // note we keep the default anonymous login credential
    // you can change it here though
    connectionSettings.host = config.addresses[address].ip;
    connectionSettings.port = config.addresses[address].port;
    console.log(connectionSettings);
    // connect the current client with the associated settings
    clients[address].connect(connectionSettings);
}

function createClient(path) {
    // initialize new client
    var c = new Client();

    // official npm documentation https://www.npmjs.com/package/ftp#events
    // tells us, that greeting returns a string so we need to pass a callback
    // to c.on('greeting', callback)
    // we could either write function(msg) { } or short form (msg) => { }
    c.on('greeting', (msg) => {
        afterGreeting(msg, c);
    });
    return c;
}

function afterGreeting(msg, client) {
    console.log(msg);

    // ready needs a callback too but returns nothing, only calls this callback
    // if ready is ready. Kappa.
    client.on('ready', () => {
        afterReady(client);
    });
}

function afterReady(client) {
    console.log('ready');
    performListing(path, client);
}

function performListing(path, client) {
    console.log('fetching from:' + path);

    // client.list returns an err if we encounter an error and a list
    // our callback is written in shortform (err, list) => { } so we're
    // passing those callback data to this anonymous function
    client.list(path, (err, list) => {
        performFetch(err, list, client);
    });
}

function performFetch(err, list, client) {
    if (err) throw err;
    list.forEach(function (element, index, array) {
        console.log('now copying: ' + element.name);
    });
    client.end();
}

Ответ на вопрос : Зависит от вашей программы.Вы всегда можете переписать и оптимизировать программу.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...