CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-ssh2-sftp-client

Promise-based SFTP client for Node.js that wraps the ssh2 module

Pending
Overview
Eval results
Files

connection-management.mddocs/

Connection Management

Connection management functionality for establishing, maintaining, and closing SFTP connections with comprehensive authentication support and event handling.

Capabilities

SftpClient Constructor

Creates a new SFTP client instance with optional name and event callbacks.

/**
 * Creates a new SFTP client instance
 * @param clientName - Optional client name for debugging (default: 'sftp')
 * @param callbacks - Optional event callbacks for error, end, and close events
 */
constructor(clientName = 'sftp', callbacks = {
  error: (err) => console.error(`Global error listener: ${err.message}`),
  end: () => console.log('Global end listener: end event raised'),
  close: () => console.log('Global close listener: close event raised')
});

Usage Examples:

const SftpClient = require('ssh2-sftp-client');

// Basic client
const sftp = new SftpClient();

// Named client with custom callbacks
const sftp = new SftpClient('myClient', {
  error: (err) => console.error('SFTP Error:', err.message),
  end: () => console.log('SFTP connection ended'),
  close: () => console.log('SFTP connection closed')
});

Connect

Establishes an SFTP connection using SSH2 configuration options.

/**
 * Create a new SFTP connection to a remote SFTP server
 * @param config - SFTP configuration object with connection details
 * @returns Promise resolving to SFTP client object
 */
connect(config): Promise<Object>;

Configuration Options:

interface ConnectionConfig {
  host: string;                    // Remote server hostname or IP
  port?: number;                   // SSH port (default: 22)
  username: string;                // Username for authentication
  password?: string;               // Password authentication
  privateKey?: string | Buffer;    // Private key for key-based auth
  passphrase?: string;             // Private key passphrase
  readyTimeout?: number;           // Connection timeout in milliseconds
  strictVendor?: boolean;          // Strict vendor checking
  debug?: Function;                // Debug function for logging
  promiseLimit?: number;           // Concurrent operation limit (default: 10)
  // Additional SSH2 options supported
}

Usage Examples:

// Password authentication
await sftp.connect({
  host: 'example.com',
  port: 22,
  username: 'user',
  password: 'password'
});

// SSH key authentication
const fs = require('fs');
await sftp.connect({
  host: 'example.com',
  username: 'user',
  privateKey: fs.readFileSync('/path/to/private/key'),
  passphrase: 'key-passphrase'
});

// With debugging and custom settings
await sftp.connect({
  host: 'example.com',
  username: 'user',
  password: 'password',
  readyTimeout: 20000,
  promiseLimit: 5,
  debug: console.log
});

End Connection

Closes the SFTP connection and cleans up resources.

/**
 * End the SFTP connection and clean up resources
 * @returns Promise resolving to true when connection is closed
 */
end(): Promise<Boolean>;

Usage Examples:

// Always end connections in finally blocks
try {
  await sftp.connect(config);
  // perform operations
} catch (err) {
  console.error(err);
} finally {
  await sftp.end();
}

// Check if connection ended successfully
const closed = await sftp.end();
if (closed) {
  console.log('Connection closed successfully');
}

Event Management

Add and remove custom event listeners for connection events.

/**
 * Add event listener to the client
 * @param eventType - Event type ('error', 'end', 'close', 'ready', etc.)
 * @param callback - Function to call when event triggers
 */
on(eventType, callback): void;

/**
 * Remove event listener from the client
 * @param eventType - Event type to remove listener for
 * @param callback - Specific callback function to remove
 */
removeListener(eventType, callback): void;

Usage Examples:

// Add custom error handler
const errorHandler = (err) => {
  console.error('Custom error handler:', err.message);
};
sftp.on('error', errorHandler);

// Add connection ready handler
sftp.on('ready', () => {
  console.log('SFTP connection is ready');
});

// Remove listener when done
sftp.removeListener('error', errorHandler);

Connection Lifecycle

  1. Create Client: Instantiate SftpClient with optional name and callbacks
  2. Connect: Call connect() with configuration object
  3. Ready: Connection established, SFTP operations available
  4. Operations: Perform file/directory operations
  5. End: Call end() to close connection and cleanup
  6. Events: Handle error, end, and close events throughout lifecycle

Authentication Methods

  • Password Authentication: Username and password
  • SSH Key Authentication: Private key with optional passphrase
  • SSH Agent: Automatic key selection via SSH agent
  • Keyboard Interactive: Interactive authentication prompts
  • Multiple Methods: Fallback authentication method support

Error Handling

Connection errors are wrapped with descriptive messages and custom error codes:

  • ERR_NOT_CONNECTED: No active SFTP connection
  • ERR_GENERIC_CLIENT: Generic client error
  • ENOTFOUND: Address lookup failed
  • ECONNREFUSED: Connection refused by remote host
  • ECONNRESET: Connection reset by remote host

Install with Tessl CLI

npx tessl i tessl/npm-ssh2-sftp-client

docs

connection-management.md

directory-operations.md

file-management.md

file-operations.md

filesystem-info.md

index.md

stream-operations.md

tile.json