我正在尝试使用 SSH 在客户端浏览器和远程服务器(“云”)之间发送文件。为此,我开发了一个 Node.js 网络服务器作为中间人。对于文件上传,我的 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()
方法。它们使用不同的实现,并且速度更快,因为它们是管道式读/写。
关于javascript - 从服务器到客户端 Node.js 的文件传输,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23708099/