1

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')

dandgore
  • 11
  • 2
  • When you pass `this.sftpClient.list` as a parameter, your separate it from it's object context (`this.sftpClient`). You can try passing `this.sftpClient.list.bind(this.sftpClient)` instead. – Pointy Feb 13 '23 at 14:01
  • Thank you, that's worked! I suspected it was something like that but my knowledge of JS isn't strong enough to have been able to know what to look for to resolve it. – dandgore Feb 13 '23 at 14:10

0 Answers0