I'm writing in node.js and using async.js and ftp client modules.
I'm using async.series and that is a function in 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);
the callback(null, true);
is for async module.
When it's run, its insert into for
loop stage._sub_directories.length
times, and then insert to client.get()
just one time (last time).
it's created one file and not more.
what is my problem? I should use another async control flow? or something else?
The way your code is written, it won't work, because you're calling an asynchronous function, client.get
, inside a regular loop.
You should replace your regular for
loop for the async.eachSeries
method, since you're already using async.js
. Try this:
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);
});
});