0

I've been trying for a while now to download a file from my SFTP file storage to my local machine - And visited a number of stack posts - Like this one:

SFTP modules in Node to download and delete files

However, I cannot get it to work. I have this code - Which is exactly the same as that posted by Mscdex in the question I have linked to - But it does not work.

const SFTPClient = require('ssh2-sftp-client');
const sftp = new SFTPClient();
const fs = require('fs');

sftp.connect({
    host: '206.189.113.33',
    port: '22',
    username: 'root',
    password: 'password'
}).then(() => {

    const remoteFilename = 'path/to/file.json';
    const localFilename = 'file.json';

    sftp.get(remoteFilename).then((stream) => {
        stream.pipe(fs.createWriteStream(localFilename));
    });

}).catch((err) => {
    console.log(err)
})

It does download a file to my local machine - However, this is a totally blank file. At first I thought it was due to the file format I need to download - .csv.gz - But even when testing with simple .json and .html files, it still downloads a blank file.

Can anyone shed some light onto why I'm running into this issue? My end goal is to download the file as a stream and push it to the client side browser via the response headers.

UPDATE

I have found a way to download the file, instead of using the npm module ssh2-sftp-client, I used npm module ssh2. I can download the file fine with this code:

var Client = require('ssh2').Client;
var connSettings = {
     host: '206.189.113.33',
     port: 22,
     username: 'root',
     password: 'password'
};

var conn = new Client();
conn.on('ready', function() {
    conn.sftp(function(err, sftp) {
        if (err) throw err;

        var moveFrom = "path/to/file.json";
        var moveTo = "file.json";

        sftp.fastGet(moveFrom, moveTo , {}, function(downloadError){
            stream.pipe(fs.createWriteStream(localFilename));
        });
    });
}).connect(connSettings);

However, Can anybody tell me how I would return a stream using this code rather than downloading the file as I want to be able to push the stream to the client and download the file in the browser.

Many thanks in advance,

G

4

1 回答 1

0

所以这是我的解决方案:

var Client = require('ssh2').Client;
    var connSettings = {
         host: '206.189.113.33',
         port: 22,
         username: 'root',
         password: 'password'
    };

var conn = new Client();
conn.on('ready', function() {
    conn.sftp(function(err, sftp) {
        if (err) throw err;

        var moveFrom = "path/to/file.json";
        var moveTo = "file.json";

        sftp.fastGet(moveFrom, moveTo , {}, function(downloadError){
            if(downloadError) throw downloadError;

            var file = 'file.json';
            res.download(file)
        });
    });
}).connect(connSettings);

似乎 ssh2 npm 模块不允许下载流。相反,我只是将文件下载到服务器上,然后将res.download()其推送回浏览器以自动开始下载。

于 2019-01-17T16:35:12.880 回答