theophilusx / ssh2-sftp-client

a client for SSH2 SFTP
Apache License 2.0
808 stars 199 forks source link

Error: get: No response from server - when .get is in forEach #506

Closed deeppaifacctum closed 9 months ago

deeppaifacctum commented 10 months ago

I am trying to get multiple files from sftp server using this code:

import SftpClient from "ssh2-sftp-client";
const sftp = new SftpClient();
await sftp.connect(sftpConfig);

//for each file in array download it
fileConfigs.forEach( async(fileConfig) => {

  const fileAsBuffer = await sftp.get(fileConfig.remoteFile);
  //do something with the buffer

})

The above fails with this error:

node_modules/ssh2-sftp-client/src/index.js:82
    const newError = new Error(msg);
                     ^

Error: get: No response from server 

The same code works if the forEach is removed. Same is observed if the sftp.get is in another async function say 'downloadFile' with the same error.

"ssh2-sftp-client": "^9.1.0"

theophilusx commented 10 months ago

THe problem is with the use of asyunc/await and .forEach. The array methods like .forEach, .reduce, .map, .filter etc are NOT async/await safe. While it is possible to use these constructs, you have to structure your code in a psecific manner to get reliable results and this aditional overhead tyupically makes the use of .forEach et. al. less clear, more error prone and more complicated than using a standard for loop.

There is lots on this (and how you can structure your code to use .forEach if you really really want to) to bb found on the web and a quick google search will find you plenty of details if interested.

Just refactor your code to use standard loops and you should be OK.