'Download from FTP with Node JS

I need help downloading more than one file from a remote FTP using Node js, the code is the following.

const FTPClient = require('ftp');
let ftp_client = new FTPClient();
const fs = require("fs");
let ftpConfig = {
     host: "remoteHost",
     port: 21,
     user: 'username',
     password: 'password',
}
//create a connection to ftp server
ftp_client.connect(ftpConfig);
ftp_client.on('ready', function() {
    ftp_client.get('/file1.csv', function(err, stream) {
      if (err) throw err;
      //stream.once('close', function() { ftp_client.end(); });
      stream.pipe(fs.createWriteStream('file1.csv'));
    });
    ftp_client.get('/dir/file2.dat', function(err, stream) {
        if (err) throw err;
        //stream.once('close', function() { ftp_client.end(); });
        stream.pipe(fs.createWriteStream('file2.dat'));
      });
      ftp_client.get('/dir/file3.dat', function(err, stream) {
        if (err) throw err;
        stream.once('close', function() { ftp_client.end(); });
        stream.pipe(fs.createWriteStream('file3.dat'));
      });
  });

And the error

Error: Unable to make data connection
    at Socket.<anonymous> (C:\Proyectos\descargar_file\node_modules\ftp\lib\connection.js:935:10)
    at Object.onceWrapper (events.js:421:28)
    at Socket.emit (events.js:327:22)
    at Object.cb (C:\Proyectos\descargar_file\node_modules\ftp\lib\connection.js:575:18)
    at Parser.<anonymous> (C:\Proyectos\descargar_file\node_modules\ftp\lib\connection.js:117:20)
    at Parser.emit (events.js:315:20)
    at Parser._write (C:\Proyectos\descargar_file\node_modules\ftp\lib\parser.js:59:10)
    at doWrite (_stream_writable.js:403:12)
    at writeOrBuffer (_stream_writable.js:387:5)
    at Parser.Writable.write (_stream_writable.js:318:11)

It is already downloading the 3 files, but also showing that error, so how can I correct this to do it in a safer way?

I also would like to add a console log while the process is downloading each file.

Thanks!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source