通过 SFTP 连接将文件流式传输到客户端

Stream file through SFTP connection to client

我正在编写一个通过 sftp 连接到文件存储的 Node Express 服务器。我正在使用 ssh2-sftp-client 包。

要检索文件,它有一个具有以下签名的 get 函数:

get(srcPath, dst, options)

dst 参数应该是字符串或 a writable stream, which will be used as the destination for a stream pipe

我想避免在我的服务器上创建文件对象,而是将文件传输到我的客户端以节省内存消耗,如 article 中所述。我尝试使用以下代码完成此操作:

const get = (writeStream) => {
    sftp.connect(config).then(() => {
        return sftp.get('path/to/file.zip', writeStream)
    });
};

app.get('/thefile', (req, res) => {
    get(res); // pass the res writable stream to sftp.get   
});

但是,这会导致我的节点服务器因未处理的承诺拒绝而崩溃。我正在尝试的是可能的吗?在发送给客户端之前,我应该先将文件存储在我的服务器机器上吗?我已经检查了 documentation/examples 中有问题的 sftp 包,但找不到我正在寻找的示例。

我发现了错误,这对我来说是一个愚蠢的错误。我忘记结束 sftp 连接。当第二次调用此方法时,它会在尝试再次连接时抛出异常。如果有人发现自己处于相同的情况,请记住在完成连接后像这样结束连接:

const get = (writeStream) => {
    sftp.connect(config).then(() => {
        return sftp.get('path/to/file.zip', writeStream);
    }).then(response => {
      sftp.end();
      resolve(response);
    });

};