0
# Connection Management
1
2
Connection management functionality for establishing, maintaining, and closing SFTP connections with comprehensive authentication support and event handling.
3
4
## Capabilities
5
6
### SftpClient Constructor
7
8
Creates a new SFTP client instance with optional name and event callbacks.
9
10
```javascript { .api }
11
/**
12
* Creates a new SFTP client instance
13
* @param clientName - Optional client name for debugging (default: 'sftp')
14
* @param callbacks - Optional event callbacks for error, end, and close events
15
*/
16
constructor(clientName = 'sftp', callbacks = {
17
error: (err) => console.error(`Global error listener: ${err.message}`),
18
end: () => console.log('Global end listener: end event raised'),
19
close: () => console.log('Global close listener: close event raised')
20
});
21
```
22
23
**Usage Examples:**
24
25
```javascript
26
const SftpClient = require('ssh2-sftp-client');
27
28
// Basic client
29
const sftp = new SftpClient();
30
31
// Named client with custom callbacks
32
const sftp = new SftpClient('myClient', {
33
error: (err) => console.error('SFTP Error:', err.message),
34
end: () => console.log('SFTP connection ended'),
35
close: () => console.log('SFTP connection closed')
36
});
37
```
38
39
### Connect
40
41
Establishes an SFTP connection using SSH2 configuration options.
42
43
```javascript { .api }
44
/**
45
* Create a new SFTP connection to a remote SFTP server
46
* @param config - SFTP configuration object with connection details
47
* @returns Promise resolving to SFTP client object
48
*/
49
connect(config): Promise<Object>;
50
```
51
52
**Configuration Options:**
53
54
```javascript { .api }
55
interface ConnectionConfig {
56
host: string; // Remote server hostname or IP
57
port?: number; // SSH port (default: 22)
58
username: string; // Username for authentication
59
password?: string; // Password authentication
60
privateKey?: string | Buffer; // Private key for key-based auth
61
passphrase?: string; // Private key passphrase
62
readyTimeout?: number; // Connection timeout in milliseconds
63
strictVendor?: boolean; // Strict vendor checking
64
debug?: Function; // Debug function for logging
65
promiseLimit?: number; // Concurrent operation limit (default: 10)
66
// Additional SSH2 options supported
67
}
68
```
69
70
**Usage Examples:**
71
72
```javascript
73
// Password authentication
74
await sftp.connect({
75
host: 'example.com',
76
port: 22,
77
username: 'user',
78
password: 'password'
79
});
80
81
// SSH key authentication
82
const fs = require('fs');
83
await sftp.connect({
84
host: 'example.com',
85
username: 'user',
86
privateKey: fs.readFileSync('/path/to/private/key'),
87
passphrase: 'key-passphrase'
88
});
89
90
// With debugging and custom settings
91
await sftp.connect({
92
host: 'example.com',
93
username: 'user',
94
password: 'password',
95
readyTimeout: 20000,
96
promiseLimit: 5,
97
debug: console.log
98
});
99
```
100
101
### End Connection
102
103
Closes the SFTP connection and cleans up resources.
104
105
```javascript { .api }
106
/**
107
* End the SFTP connection and clean up resources
108
* @returns Promise resolving to true when connection is closed
109
*/
110
end(): Promise<Boolean>;
111
```
112
113
**Usage Examples:**
114
115
```javascript
116
// Always end connections in finally blocks
117
try {
118
await sftp.connect(config);
119
// perform operations
120
} catch (err) {
121
console.error(err);
122
} finally {
123
await sftp.end();
124
}
125
126
// Check if connection ended successfully
127
const closed = await sftp.end();
128
if (closed) {
129
console.log('Connection closed successfully');
130
}
131
```
132
133
### Event Management
134
135
Add and remove custom event listeners for connection events.
136
137
```javascript { .api }
138
/**
139
* Add event listener to the client
140
* @param eventType - Event type ('error', 'end', 'close', 'ready', etc.)
141
* @param callback - Function to call when event triggers
142
*/
143
on(eventType, callback): void;
144
145
/**
146
* Remove event listener from the client
147
* @param eventType - Event type to remove listener for
148
* @param callback - Specific callback function to remove
149
*/
150
removeListener(eventType, callback): void;
151
```
152
153
**Usage Examples:**
154
155
```javascript
156
// Add custom error handler
157
const errorHandler = (err) => {
158
console.error('Custom error handler:', err.message);
159
};
160
sftp.on('error', errorHandler);
161
162
// Add connection ready handler
163
sftp.on('ready', () => {
164
console.log('SFTP connection is ready');
165
});
166
167
// Remove listener when done
168
sftp.removeListener('error', errorHandler);
169
```
170
171
## Connection Lifecycle
172
173
1. **Create Client**: Instantiate SftpClient with optional name and callbacks
174
2. **Connect**: Call `connect()` with configuration object
175
3. **Ready**: Connection established, SFTP operations available
176
4. **Operations**: Perform file/directory operations
177
5. **End**: Call `end()` to close connection and cleanup
178
6. **Events**: Handle error, end, and close events throughout lifecycle
179
180
## Authentication Methods
181
182
- **Password Authentication**: Username and password
183
- **SSH Key Authentication**: Private key with optional passphrase
184
- **SSH Agent**: Automatic key selection via SSH agent
185
- **Keyboard Interactive**: Interactive authentication prompts
186
- **Multiple Methods**: Fallback authentication method support
187
188
## Error Handling
189
190
Connection errors are wrapped with descriptive messages and custom error codes:
191
192
- `ERR_NOT_CONNECTED`: No active SFTP connection
193
- `ERR_GENERIC_CLIENT`: Generic client error
194
- `ENOTFOUND`: Address lookup failed
195
- `ECONNREFUSED`: Connection refused by remote host
196
- `ECONNRESET`: Connection reset by remote host