【问题标题】:File transfer from server to client Node.js从服务器到客户端 Node.js 的文件传输
【发布时间】:2014-05-17 05:54:54
【问题描述】:

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

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

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

任何帮助将不胜感激!

【问题讨论】:

    标签: javascript node.js ssh


    【解决方案1】:

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

    【讨论】:

    • 我试过了,但我得到了“权限被拒绝”...虽然我很确定我有读取服务器上文件的权限。
    【解决方案2】:

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

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

    确保节点应用有权替换文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多