I'm getting an error when downloading multiple files from an SFTP site using the ssh2-sftp-client
library. The error thrown seems to indicate that the node stream is not getting cleared after each download completes. This is causing a memory leak in my app. In production I need to be able to download thousands of files so this memory leak is substantial. How can I close the stream so that the memory is released after each file is downloaded?
code:
const Client = require('ssh2-sftp-client');
const sftp = new Client();
sftp.connect({
host: '195.144.107.198',
port: 22,
username: 'demo',
password: 'password'
}).then(async () => {
const fileNames = ['readme.txt', 'readme.txt', 'readme.txt', 'readme.txt', 'readme.txt', 'readme.txt', 'readme.txt', 'readme.txt', 'readme.txt', 'readme.txt', 'readme.txt', 'readme.txt'];
// Loop through filenames
for (let i = 0; i < fileNames.length; i++) {
// Download all the files synchronously (1 at a time)
const fileName = fileNames[i];
await new Promise((resolve, reject) => { // <-- note the await
sftp.get(fileName, true, 'utf8').then((stream) => {
let text = '';
stream
.on('data', (d) => { text += d; })
.on('end', () => {
console.log('Success downloaded file', i);
resolve(text);
});
}).catch((err) => {
console.log('Error downloading file', err);
reject(err.message)
});
});
}
sftp.end();
});
Note: this code uses a public SFTP site so the credentials are not sensitive and you can run it for testing. Found here: https://www.sftp.net/public-online-sftp-servers
Error (occurs after file #9 is downloaded):
(node:44580) MaxListenersExceededWarning: Possible EventEmitter memory leak detected.
11 error listeners added. Use emitter.setMaxListeners() to increase limit