AliKhokhar
AliKhokhar

Reputation: 55

File transfer from server to client Node.js

I'm trying to send files between client side browser and a remote server ('the cloud') using SSH. For this, I've developed a Node.js webserver as a middleman. For file uploads, my Node webserver receive requests from the user and uses the ssh2 module to transfer it to the remote server. The following is a snippet of the code. The file upload works perfectly:

var readStream = fs.createReadStream( "filename.txt" ); // on client's local computer
var writeStream = sftp.createWriteStream( "/path/to/file/filename.txt" ); // on the remote server

writeStream.on('close', function () {
    console.log( "- file transferred to cloud" );
    sftp.end();
    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.end("The file has been successfully uploaded to the cloud!");
});
readStream.pipe( writeStream );

So I try to use the same idea to transfer files the OTHER way: from the remote server to the client and here's my code:

var readStream = sftp.createReadStream( "/path/to/file/filename.txt" ); // on remote server
var writeStream = fs.createWriteStream( "path/filename.txt" ); // on the client's local computer server

writeStream.on('close', function () {
    console.log( "- file transferred to cloud" );
    sftp.end();
    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.end("The file has been successfully uploaded to the cloud!");
});
readStream.pipe( writeStream );

The problem is that the file on the server is indeed read and a file is created on the client side - but it has no data! I can't figure out why the data isn't being transferred from the server to the client but the same way works if I transfer a file from client to server.

Any help would be much appreciated!

Upvotes: 0

Views: 3670

Answers (2)

Ovidiu Alexa
Ovidiu Alexa

Reputation: 1

Please look at the definition: https://nodejs.org/api/fs.html#fs_fs_createwritestream_path_options

flags <string> See support of file system flags. Default: 'w'.

Make sure the node app has permission to replace the file.

Upvotes: 0

mscdex
mscdex

Reputation: 106696

Try the sftp.fastGet() and sftp.fastPut() methods instead. They use a different implementation and are much faster because they pipeline reads/writes.

Upvotes: 1

Related Questions