jesica
jesica

Reputation: 685

File upload error in easy-ftp with electron & node.js app

I am trying to upload csv files in remote ftp using easy-ftp package but sometimes uploads & sometimes showing error like below image

enter image description here

here is my code

let ftp = new EasyFtp();
try{
    const config = {
        host: 'ftp.saba.com',
        port: 21,
        username: 'username',
        password: 'password',
        type : 'ftp'
    };
    ftp.connect(config);
    ftp.upload(csvName, "/csvs/", function (err) {
        try {
            fs.unlink(csvName, (err) => {
                if (err) {
                    console.log(err);
                    return;
                }
            });
        } catch(error) {
            console.log(error);
        }
    });
} catch(error) {
    console.log(error);
}

I can't find any helpful resources to overcome this issue, what can I do now?

Thanks

Upvotes: 1

Views: 698

Answers (1)

shaochuancs
shaochuancs

Reputation: 16226

This is an asynchronous problem. You need to upload file after the connect is successful.

The code should be:

ftp.on('open', function(){
  ftp.upload(csvName, "/csvs/", function (err) {
    // process upload result
  });
});

ftp.connect(config);

In your code, the upload request is sent immediately after the connect operation. If lucky, when easy-ftp try to deliver the upload operation, the previous connect is already finished and successful, then upload would be successful too.

If unlucky, when easy-ftp try to deliver the upload operation, the previous connect is still not finished yet. Then the upload will fail and show "Cannot read property..." error (looks like easy-ftp should display some better error message).

To solve the problem, you need to listen the "open" event in easy-ftp, and only upload files when that event has been emitted:

open(< FTPClient >client) - Emitted when connection and authentication were sucessful.

Upvotes: 2

Related Questions