Skip to content

Instantly share code, notes, and snippets.

@midnightcodr
Created December 26, 2020 18:17
Show Gist options
  • Save midnightcodr/33ccbf19f2e7621f556a9e5cc6ac537c to your computer and use it in GitHub Desktop.
Save midnightcodr/33ccbf19f2e7621f556a9e5cc6ac537c to your computer and use it in GitHub Desktop.
ssh2-sftp-client reconnect on error demostration
SFTP_USER=
SFTP_HOST=127.0.0.1
SFTP_PORT=22
SFTP_PASSWORD=
require('dotenv').config()
const max = 1000
const SftpClient = require('ssh2-sftp-client')
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))
const { SFTP_HOST, SFTP_USER, SFTP_PORT, SFTP_PASSWORD } = process.env
const sftpConfig = {
host: SFTP_HOST,
port: SFTP_PORT,
username: SFTP_USER,
password: SFTP_PASSWORD,
// keepaliveInterval: 30,
retries: 30,
retry_minTimeout: 5000
}
console.log(sftpConfig)
const reconnect = async oldSftp => {
if (oldSftp !== undefined) {
try {
await oldSftp.end()
} catch (err) {
console.log('not able to call end() on the original sftp client: ', err)
}
}
const sftp = new SftpClient()
await sleep(5000)
await sftp.connect(sftpConfig)
return sftp
}
const run = async () => {
let sftp = await reconnect()
sftp.on('error', async error => {
console.log(`sftp error handling: ${error.message}`)
sftp = await reconnect(sftp)
})
const listDir = async () => {
let listFiles
try {
listFiles = await sftp.list('/', '*.txt')
const files = listFiles.map(f => f.name)
return files
} catch (err) {
console.log(`list: sftp error: ${err.message}`)
sftp = await reconnect()
return []
}
}
for (let cnt = 0; cnt < max; cnt++) {
console.time(`listing-${cnt}`)
console.log(await listDir())
console.timeEnd(`listing-${cnt}`)
await sleep(2000)
}
}
run()
// to test, 1. create .env based on .env.example 2. run `node index.js`,
// after some seconds, reboot the target sftp server and watch the listing
// continues after sftp server is back on line again.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment