文件从服务器传输到客户端Node.js

File transfer from server to client Node.js

本文关键字:客户端 Node js 传输 服务器 文件      更新时间:2023-09-26

我正在尝试使用SSH在客户端浏览器和远程服务器('云')之间发送文件。为此,我开发了一个Node.js web服务器作为中间人。对于文件上传,我的Node web服务器接收来自用户的请求,并使用ssh2模块将其传输到远程服务器。下面是代码片段。文件上传工作完美:

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 );

所以我尝试使用相同的想法来传输文件的另一种方式:从远程服务器到客户端,这是我的代码:

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 );

问题是服务器上的文件确实被读取并且在客户端创建了一个文件-但是它没有数据!我不明白为什么数据没有从服务器传输到客户端,但如果我将文件从客户端传输到服务器,同样的方式可以工作。

任何帮助将非常感激!

试试sftp.fastGet()sftp.fastPut()的方法。它们使用不同的实现,并且速度更快,因为它们是管道读/写。

请查看定义:https://nodejs.org/api/fs.html#fs_fs_createwritestream_path_options

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