ssh2-sftp-client throwing an error when client function is passed as parameter

509 Views Asked by At

I'm using the ssh2-sftp-client library with Typescript to connect to an sftp server - the connection works, however when I create a wrapper function to include the 'connect' and 'end' functions around the main function call I get an error from the main function being called.

The wrapper function:

private async session(callback: Function, ...args): Promise<any> {
    let output;

    await this.sftpClient.connect(credentials);

    try {
      output = await callback(...args);
    } catch (err) {
      throw err;
    } finally {
      await this.sftpClient.end();
    }

    return output;
  }

The calling function:

async getFilesList(path: string): Promise<object[]> {
      return await this.session(this.sftpClient.list, path);
  }

The error received: list: Error removing temp listeners: Cannot read properties of null (reading 'removeListener')

If I call the function directly (replace callback(...args) with this.sftpClient.list(...args)) then it works fine.

If I use this: output = await callback.apply(this, args) then I get a slightly different error: list: Error removing temp listeners: Cannot read properties of undefined (reading 'end')

0

There are 0 best solutions below