ftp客户端使用异步javascript

时间:2015-06-08 13:16:30

标签: javascript node.js asynchronous ftp ftp-client

我正在使用node.js编写并使用async.js和ftp客户端模块 我正在使用 async.series ,这是async.series中的一个函数:

    var client = new ftp();
client.on('ready', function () {
    for ( var i = 0  ; i < stage._sub_directories.length ; i++ ) {
        var path = get_absolute_path() + DIRECTORY_NAME_LESSONS + stage._name + "/" + DIRECTORY_NAME_STAGE + stage._sub_directories[i];
        var file = 'copy.' + stage._sub_directories[i] + get_xml_file_name();
        client.get(path + "/" + get_xml_file_name(), function (err, stream) {
            console.log('done');
            if (err) throw err;
            stream.once('close', function () {client.end();});
            stream.pipe(fs.createWriteStream(file));
            callback(null, true);
        });
    }
});
client.connect(config);

callback(null, true);用于异步模块。 当它运行时,它插入for循环stage._sub_directories.length次,然后只插入client.get()一次(上次)。
它创建了一个文件而不是更多。
我的问题是什么?我应该使用另一个异步控制流程?或者是其他东西?

2 个答案:

答案 0 :(得分:0)

编写代码的方式,它不会起作用,因为你在常规循环中调用异步函数client.get

您应该替换for方法的常规async.eachSeries循环,因为您已经在使用async.js。试试这个:

client.on('ready', function () {
    async.eachSeries(stage._sub_directories, function (subDir, done) {
        var path = get_absolute_path() + DIRECTORY_NAME_LESSONS + stage._name + "/" + DIRECTORY_NAME_STAGE + subDir;
        var file = 'copy.' + subDir + get_xml_file_name();
        client.get(path + "/" + get_xml_file_name(), function (err, stream) {
            if (err) return done(err);
            console.log('done');
            stream.once('close', function () {client.end();});
            stream.pipe(fs.createWriteStream(file));
            done();
        });
    }, function (err) {
        if (err) return callback(err);
        callback(null, true);
    });
});

答案 1 :(得分:0)

老实说令人沮丧的是需要多少标记和发现来“解决”这些当前流行的FTP模块...我是FTPimp的作者,我专门写这篇文章来解决这种挫败感。 例如,你可以使用 ftpimp模块做同样的事情:

ftp.connect(function () {
    stage._sub_directories.forEach(function (subDir) {
        var path = get_absolute_path() + DIRECTORY_NAME_LESSONS + stage._name + "/" + DIRECTORY_NAME_STAGE + subDir;
        var file = 'copy.' + subDir + get_xml_file_name();
        //save from -> to
        ftp.save([path + "/" + get_xml_file_name(), file], function (err, name) {
            console.log(err, name);
        });
    });
    //@see http://ftpimp.net/FTP.html#event:queueEmpty
    ftp.once('queueEmpty', function () {
        console.log('files saved');
        //do more stuff ...
        ftp.quit();
    });
});
相关问题