Pritiranjan Mishra
Pritiranjan Mishra

Reputation: 103

error in download file from sftp using node js

I am trying to download a file from the server. I am able to connect to the sftp , list all the files in the given directory. However after downloading the file seems to be corrupted . I am unable to open that. Also I get an error while downloading as below

UnhandledPromiseRejectionWarning: TypeError: data.on is not a function 

Here is the code

const Client = require('ssh2-sftp-client');
let sftp = new Client;
  sftp.connect(config).then(() => { 
    sftp.get(remotePath).then((data) => {
      var outFile = fs.createWriteStream('fileee.zip')
      outFile.on('data',function(response) {
        outFile.write(response);
      });
      outFile.on('close', function() {
        outFile.close();
      });
    });
  })

Upvotes: 0

Views: 732

Answers (1)

derpirscher
derpirscher

Reputation: 17382

Citing from the docs

let client = new Client();

let remotePath = '/remote/server/path/file.txt';
let dst = fs.createWriteStream('/local/file/path/copy.txt');

client.connect(config)
  .then(() => {
    return client.get(remotePath, dst);
  })
  .then(() => {
    client.end();
  })
  .catch(err => {
    console.error(err.message);
  });

Don't know where you got the idea about data.on() ...

Upvotes: 1

Related Questions