Export files to SFTP in Node.js with ssh2-sftp-client

Secure file transfers are crucial for protecting sensitive data. SFTP (Secure File Transfer
Protocol) is a reliable method for securely transferring files over a network. In this DevTip, we'll
explore how to use Node.js and the open-source library ssh2-sftp-client
to efficiently handle file
transfers to and from an SFTP server. ssh2-sftp-client
is a convenient, promise-based wrapper
around the powerful ssh2
library, simplifying SFTP operations.
Introduction to SFTP
SFTP is a secure protocol built on SSH (Secure Shell) that provides encrypted file transfers. It ensures data integrity and confidentiality, making it ideal for transferring sensitive information.
Setting up your Node.js environment
Ensure you have Node.js installed. ssh2-sftp-client
version 12.x (current stable) supports Node.js
versions 20.x and higher. Versions prior to 20.x are not supported. You can verify your installation
by running:
node -v
npm -v
Installing and configuring ssh2-sftp-client
Install the ssh2-sftp-client
library using npm:
npm install ssh2-sftp-client
Connecting, uploading, downloading, and error handling
Here's how you can establish a connection, upload a file, download a file, and handle errors robustly:
const Client = require('ssh2-sftp-client')
const fs = require('fs') // Required for the dummy file creation
async function main() {
const sftp = new Client()
const config = {
host: 'your.sftp.server',
port: 22, // Use an integer for the port
username: 'your-username',
password: 'your-password',
// For testing against a non-existent server, you might add a timeout
// readyTimeout: 5000 // e.g., 5 seconds
}
const localPath = './local-file.txt'
const remotePath = '/remote/path/file.txt'
const localDownloadPath = './downloaded-file.txt'
// Create a dummy file for upload example if it doesn't exist
if (!fs.existsSync(localPath)) {
fs.writeFileSync(localPath, 'This is a test file for SFTP upload.')
console.log(`Created dummy ${localPath} for testing.`)
}
try {
await sftp.connect(config)
console.log('Connected successfully to SFTP server.')
// Uploading files
console.log(`Attempting to upload ${localPath} to ${remotePath}...`)
await sftp.put(localPath, remotePath)
console.log('File uploaded successfully.')
// Downloading files
console.log(`Attempting to download ${remotePath} to ${localDownloadPath}...`)
await sftp.get(remotePath, localDownloadPath)
console.log('File downloaded successfully.')
} catch (err) {
console.error('An error occurred:', err.message)
// More specific error handling can be added here based on err.code or err.level
} finally {
try {
await sftp.end()
console.log('Connection closed.')
} catch (err) {
console.error('Error closing connection:', err.message)
}
}
}
main().catch(console.error) // Ensure top-level errors from main are caught
In the example above, we've wrapped our SFTP operations within an async
function called main
.
This function handles connecting to the server, uploading a file, and then downloading it. The
try...finally
block ensures that the SFTP connection is closed using sftp.end()
regardless of
whether the operations were successful or an error occurred. We also create a dummy local-file.txt
to ensure the upload example can run.
Best practices for secure and efficient file transfers
- Always use strong authentication methods. For enhanced security, using SSH key-based
authentication is highly recommended. The
privateKey
option in theconnect
config can be used for this. Refer to thessh2-sftp-client
andssh2
documentation for detailed examples. - Regularly update your libraries and dependencies.
- Validate file paths and permissions.
- Implement logging and monitoring for file transfers.
Conclusion and practical use cases
Using ssh2-sftp-client
simplifies secure file transfers in Node.js applications. This approach is
ideal for automated backups, data synchronization, and secure file exchanges between systems.
For a streamlined solution, consider Transloadit's 🤖 /sftp/store Robot as part of our File Exporting service.