Registry / http-networking / ssh2-sftp-client

ssh2-sftp-client

JSON →
library12.1.1jsnpmunverified

ssh2-sftp-client is a promise-based SFTP client for Node.js, acting as a decorator around the robust `ssh2` package. It provides a convenient, promise-driven API for common SFTP operations such as connecting, listing directories, uploading, downloading, and managing files, abstracting away the event-based complexities of the underlying `ssh2` library. The current stable release is v12.1.1, indicating active maintenance with a regular cadence of minor and patch updates, alongside major versions for significant API changes. It officially supports Node.js versions 20.x and newer, specifically tested against Node 24.14.0, and includes specific fixes for platform quirks like those found in Microsoft SFTP servers. Its focus on promises, active bug fixing, and direct integration with the `ssh2` library makes it a reliable solution for SFTP interactions in modern Node.js environments.

npm install ssh2-sftp-client
INSTALL
IMPORT
SIG · SSH2-SFTP-CLIENT
S
ssh2-sftp-client
http-networkingjavascriptv12.1.1
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

SftpClient
import SftpClient from 'ssh2-sftp-client';
import { SftpClient } from 'ssh2-sftp-client';
The SftpClient class is exported as the default export. Named imports like `{ SftpClient }` will result in an undefined SftpClient object.
SftpClient (CJS)
const SftpClient = require('ssh2-sftp-client');
Standard CommonJS import pattern for the default-exported SftpClient class.
ConnectConfig (Type)
import type { ConnectConfig } from 'ssh2-sftp-client';
import { ConnectConfig } from 'ssh2-sftp-client';
TypeScript type definitions for the `connect` method's configuration object are available. Use `import type` to avoid bundling the type definition at runtime.

Demonstrates connecting to an SFTP server, creating a directory, uploading, listing, downloading, and deleting a file, including error handling and resource cleanup.

import SftpClient from 'ssh2-sftp-client'; import path from 'path'; import fs from 'fs/promises'; async function sftpExample() { const sftp = new SftpClient(); const host = process.env.SFTP_HOST ?? 'sftp.example.com'; const port = parseInt(process.env.SFTP_PORT ?? '22', 10); const username = process.env.SFTP_USERNAME ?? 'user'; const password = process.env.SFTP_PASSWORD ?? 'password'; // Or use privateKey: fs.readFileSync('~/.ssh/id_rsa') const remoteDir = '/home/user/uploads'; const remoteFile = path.join(remoteDir, 'test_upload.txt'); const localFileToUpload = 'local_file.txt'; const localFileToDownload = 'downloaded_file.txt'; try { console.log(`Attempting to connect to ${username}@${host}:${port}...`); await sftp.connect({ host, port, username, password }); console.log('Successfully connected to SFTP server.'); // Ensure the remote directory exists await sftp.mkdir(remoteDir, true); // Create a dummy local file for upload await fs.writeFile(localFileToUpload, 'Hello from Node.js SFTP client!'); console.log(`Uploading ${localFileToUpload} to ${remoteFile}...`); await sftp.put(localFileToUpload, remoteFile); console.log('File uploaded successfully.'); // List contents of the remote directory console.log(`Listing contents of ${remoteDir}:`); const list = await sftp.list(remoteDir); list.forEach(item => console.log(` - ${item.name} (${item.type})`)); // Download the uploaded file console.log(`Downloading ${remoteFile} to ${localFileToDownload}...`); await sftp.get(remoteFile, localFileToDownload); console.log('File downloaded successfully.'); // Verify downloaded content (optional) const downloadedContent = await fs.readFile(localFileToDownload, 'utf8'); console.log('Downloaded content:', downloadedContent); // Delete the remote file console.log(`Deleting remote file ${remoteFile}...`); await sftp.delete(remoteFile); console.log('Remote file deleted.'); } catch (err) { console.error('SFTP operation failed:', err.message); } finally { if (sftp.sftp) { // Check if the internal SFTP object exists (implies connection was made) console.log('Disconnecting from SFTP server.'); await sftp.end(); } // Clean up local test files await fs.unlink(localFileToUpload).catch(() => {}); await fs.unlink(localFileToDownload).catch(() => {}); console.log('Local temporary files cleaned up.'); } } sftpExample();
Debug
Known issues
breakingThe connection retry support was removed in v12.0.0. Applications previously relying on automatic retries must implement their own retry logic or ensure robust error handling for immediate connection failures.
fix
Implement custom retry logic using a loop or a dedicated retry utility, or ensure robust error handling for initial connection attempts without expecting automatic retries from the library.
affects: >=12.0.0
breakingThe event handling strategy changed significantly in v11.0.0. Global event listeners no longer raise errors by default; they now primarily log events and invalidate the connection object. Custom global event listeners must be passed into the constructor to handle errors as needed.
fix
Review existing event handlers. If you rely on errors being thrown from global listeners, provide a custom event handler in the SftpClient constructor or adapt to the new logging/invalidation behavior for global events.
affects: >=11.0.0
breakingThe package officially dropped support for Node.js versions prior to v20.x. Running on older Node.js environments may lead to unexpected behavior, errors, or security vulnerabilities due to underlying dependency updates.
fix
Upgrade your Node.js environment to version 20.x or higher to ensure compatibility, stability, and access to the latest features and security patches.
affects: >=12.0.0
gotchaSftpClient objects are not designed for re-use after a connection has been terminated or failed. Attempting to re-use an SftpClient instance after calling `.end()` or after a connection error can lead to unpredictable behavior, hanging promises, or silent failures.
fix
Always instantiate a new SftpClient object for each new connection attempt, especially after a successful disconnect or a connection error. Do not store and reuse `sftp` instances across multiple distinct operations.
affects: *
breakingSecurity update: Version 10.0.0 bumped the underlying 'ssh2' dependency to 1.15.0 to fix CVE-2023-48795. Older versions of `ssh2-sftp-client` (prior to v10.0.0) are vulnerable to this security flaw.
fix
Upgrade to `ssh2-sftp-client` version 10.0.0 or higher to mitigate CVE-2023-48795 and ensure secure SFTP connections.
affects: <10.0.0
gotchaConnections can reset unexpectedly (ECONNRESET) due to remote server issues, which could previously lead to delayed timeouts or hanging promises if the internal connection state wasn't properly invalidated. This was addressed in v12.1.1, but it remains an important edge case to handle.
fix
Ensure you are on version 12.1.1 or higher to benefit from the fix. Implement robust error handling for network events and consider using connection health checks if persistent connections are critical, as `ECONNRESET` signifies an abrupt server-side closure.
affects: <12.1.1
Errors
Common errors & fixes
Error: Timeout while waiting for handshake
Issues with network connectivity, firewall settings, or incorrect server configuration preventing the SSH handshake from completing within the default timeout period.
fix
Verify server host, port, and network accessibility. Check firewall rules on both client and server. Increase the 'timeout' option in the `connect` method if the server is known to be slow to respond, e.g., `sftp.connect({ ..., timeout: 10000 })`.
ECONNRESET
The remote SFTP server unexpectedly closed the TCP connection. This can happen due to server load, idle timeouts, or specific server-side issues.
fix
Ensure your `ssh2-sftp-client` version is >= 12.1.1 to correctly handle these events and invalidate the internal connection state. Review server logs for reasons behind the connection termination. Implement application-level retry logic for operations that might be interrupted by such events.
UnhandledPromiseRejectionWarning: SftpClient: Error: Not returning the promise in a then() block
A promise chain within a `.then()` block does not explicitly return the result of the subsequent asynchronous operation, causing the outer promise to resolve prematurely or errors to not propagate correctly.
fix
Always return promises from within `.then()` blocks to ensure proper chaining and error propagation. For example, use `return sftp.list(path)` instead of just `sftp.list(path)`.
Connection hangs or fails for larger files
Default promise concurrency limits (especially with `uploadDir`/`downloadDir`) or network bottlenecks affecting large file transfers. This was particularly noticeable before the `promiseLimit` setting was introduced and tuned.
fix
Adjust the `promiseLimit` option in methods like `uploadDir`/`downloadDir` (default is 10) to optimize for your environment. Experiment with values, but avoid excessively high limits which can degrade performance. Ensure sufficient server resources and network bandwidth.
Upgrade
Version history
12.1.1latest on npm
Audit
Dependencies
ssh2requiredCore underlying SSH2 implementation that ssh2-sftp-client wraps and extends with a promise-based API.
Agent activity
36 hits · last 30 days
node
30
OpenAI (training)
2
Resources