3

I'm using the npm ftp library: https://www.npmjs.com/package/ftp I want to upload a file on a ftp server and I want to catch errors during the connection, e.g. a wrong login.

My function:

const upload = () => {

    try {
        const ftpClient = new ftp();
        fs.readFile(filePathToUpload, 'utf8', (err, data) => {
            const fileValue = data.concat(' Timestamp: ', new Date());

            ftpClient.on('ready', () => {
                ftpClient.put(fileValue, FILENAME_REMOTE, (err) => {
                    console.log('PUT FTP');
                    if (err) {
                        console.log(err);
                    }
                    ftpClient.end();
                });
            });

            try {
                console.log('connect upload');
                ftpClient.connect(ftpConfig);
            } catch (connectionError) {
                console.log('Connection Error: ', connectionError);
            }
        });
    } catch (err) {
        console.log('ERROR-FTP-Upload: ', err);
    }
};

But I always get 'ERROR Uncaught Exception' even if I use

process.on('uncaughtException', err => console.log(err));

Full Stack Trace:

{"errorType":"Error","errorMessage":"Login incorrect.","code":530,"stack":["Error: Login incorrect.","    at makeError (/var/task/node_modules/ftp/lib/connection.js:1067:13)","    at Parser.<anonymous> (/var/task/node_modules/ftp/lib/connection.js:113:25)","    at Parser.emit (events.js:189:13)","    at Parser.EventEmitter.emit (domain.js:441:20)","    at Parser._write (/var/task/node_modules/ftp/lib/parser.js:59:10)","    at doWrite (_stream_writable.js:410:12)","    at writeOrBuffer (_stream_writable.js:394:5)","    at Parser.Writable.write (_stream_writable.js:294:11)","    at Socket.ondata (/var/task/node_modules/ftp/lib/connection.js:273:20)","    at Socket.emit (events.js:189:13)"]}

How can I handle the error?

A.Service
  • 359
  • 3
  • 6
  • 16
  • use try catch inside the callback, readFile is async – 3960278 Jul 09 '19 at 10:12
  • @Suryapratap Singh I also tried this before. I added this to the original question. Do you mean like that? – A.Service Jul 09 '19 at 10:16
  • 1
    all i mean is try catch will not work for async operations directly, if there is any other async method inside callback, it will still not work – 3960278 Jul 09 '19 at 10:23

1 Answers1

1
const ftpClient = new ftp();
ftpClient.on('error',console.dir);//add error listener.
// rest code...
lx1412
  • 1,160
  • 6
  • 14
  • This does not work for me, the error function is never called. I get this error inside of the 'ready' function inside the `ftpClient.get(` call and it does not tell me what is causing the problem. – Guntram Jun 28 '23 at 13:19
  • My problem was that I tried to get the file by its complete path, but I should have used the filename only. – Guntram Jun 28 '23 at 13:34