我正在尝试使用SSH在客户端浏览器和远程服务器(“云”)之间发送文件。为此,我开发了一个Node.js网络服务器作为中间人。对于文件上传,我的Node webserver接收来自用户的请求,并使用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 );
问题是服务器上的文件确实已读取,并且在客户端创建了一个文件 - 但它没有数据!我无法弄清楚为什么数据没有从服务器传输到客户端,但是如果我将文件从客户端传输到服务器,则同样的方式。
非常感谢任何帮助!
答案 0 :(得分:1)
请尝试使用sftp.fastGet()
和sftp.fastPut()
方法。它们使用不同的实现,速度更快,因为它们管道读/写。
答案 1 :(得分:0)
请查看定义:https://nodejs.org/api/fs.html#fs_fs_createwritestream_path_options
flags <string> See support of file system flags. Default: 'w'.
确保节点应用具有替换文件的权限。