The React Native SSH SFTP library manages SSH and SFTP connections through a well-defined lifecycle. Understanding this lifecycle is crucial for proper resource management.
All SFTP methods (sftpLs, sftpDownload, sftpUpload, etc.) automatically call an internal checkSFTP() method that establishes the connection if it’s not already active:
const client = await SSHClient.connectWithPassword(host, port, username, password);// No need to call connectSFTP() firstconst files = await client.sftpLs('/home/user');
Use disconnectSFTP() to close the SFTP connection while keeping the SSH connection active:
client.disconnectSFTP();
On iOS, disconnectSFTP() has limited functionality due to native implementation constraints. The SSH disconnect() method will properly close the SFTP stream on all platforms.
From the source code (sshclient.ts:696-707):
disconnectSFTP(): void { // TODO This require a fix in the native part. I don't care. // It actually still work since the native code disconnect() will actually // close the sftp stream. // Only downside is we can't *explicitly* close the sftp channel. if (Platform.OS !== 'ios') { this.unregisterNativeListener(NATIVE_EVENT_DOWNLOAD_PROGRESS); this.unregisterNativeListener(NATIVE_EVENT_UPLOAD_PROGRESS); RNSSHClient.disconnectSFTP(this._key); this._activeStream.sftp = false; }}