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