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:
Copy
Ask AI
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:
Copy
Ask AI
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):
Copy
Ask AI
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; }}
Use disconnect() to close all active connections (shell, SFTP, and SSH):
Copy
Ask AI
client.disconnect();
From the source code (sshclient.ts:715-726):
Copy
Ask AI
disconnect(): void { if (this._activeStream.shell) { this.closeShell(); } if (this._activeStream.sftp) { this.disconnectSFTP(); } // TODO this should use a callback too RNSSHClient.disconnect(this._key);}