title: nodejs download files from sftp
body: <p>I need to download some <code>.txt.pgp</code> files from <code>sftp</code>. I've tried <strong>npm</strong> <code>ssh2</code>, <code>ssh2-sftp-client</code> and <code>node-ssh</code> without any success.</p>
  
  <p>The closest I got so far is the list of the files in the remote folder using <code>sftp.readdir</code> (<code>ssh2</code>) or <code>sftp.list</code> (<code>ssh2-sftp-client</code>).</p>
  
  <p>I've tried <code>pipe</code> and <code>fs.createWriteStream</code> and <code>sftp.fastGet</code> but there's no file saved on my local machine.</p>
  
  <pre><code>const conn = new Client();
  conn.on('ready', () =&gt; {
      console.log('Client :: ready');
  
      conn.sftp((err, sftp) =&gt; {
          if (err) throw err;
  
          sftp.readdir('out', (err, list) =&gt; {
              if (err) throw err;
  
              list.forEach(item =&gt; {
                  console.log(item.filename);
  
                  const fileName = item.filename;
  
                  sftp.fastGet(fileName, fileName, {}, downloadError =&gt; {
                      if(downloadError) throw downloadError;
  
                      console.log("Succesfully uploaded");
                  });
              })
              conn.end();
          });
      });
  }).connect(config);
  </code></pre>
  
  <p><strong>OR</strong></p>
  
  <pre><code>const Client = require('ssh2-sftp-client');
  const sftp = new Client();
  
  sftp.connect(config).then(() =&gt; {
      return sftp.list('out');
  })
  .then(files =&gt; {
      // console.log(files);
      if (files.length &gt; 0) {
          console.log('got list of files!');
      }
  
      files.map(file =&gt; {
          const fileName = file.name;
  
          sftp.get(fileName)
          .then(() =&gt; {
              fs.writeFile(fileName);
          }); 
      })
  })
  .then(() =&gt; {
      sftp.end();
  }).catch((err) =&gt; {
      console.log(err);
  });
  </code></pre>