简体   繁体   中英

ssh2-sftp-client Get request node.js

I am currently attempting to download a file from an FTP server using ssh2-sftp-client.

I can see the list of the files as shown in the code below, my problem is when it comes to downloading the files.

As you can see from my code below I am attempting to use the sftp.get to get the contents of the file and node file system to create a file.

When the file saves it doesn't save the contents of the file on the server is only saves [object Object]

var Client = require('../../node_modules/ssh2-sftp-client');
var sftp = new Client();
var root = '/files';
var fs = require('fs');

sftp.connect({
  host: '192.168.0.1',
  port: '22',
  username: 'user',
  password: 'password'
}).then(() => {
  return sftp.list(root);
}).then((data) => {
  for( var i = 0, len = data.length; i < len; i++) {
    console.log(data[i].name);
    var name = data[i].name;
    sftp.get(root+'/'+name).then((file) => {
      console.log(file);
      fs.writeFile('downloads/'+name, file, function(err) {
      if(err) {
        return console.log(err);
      }
      console.log("The file was saved!");
    });
  })      }
}).catch((err) => {
  console.log(err, 'catch error');
});

How can I get this to save the contents of the file?

Any help or a push in the right direction would be very appreciated.

I resolved my problem by changing the sftp.get to the following:-

sftp.get(root+"/"+name).then((stream) => {
  stream.pipe(fs.createWriteStream(local+name));
});

I hope this helps anybody else who might have this issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM