在使用node.js中的sftp将流发送到远程文件路径时,正在上传空文件

时间:2019-05-08 03:55:18

标签: node.js sftp filestream

我想通过使用sftp的流将数据发送到远程服务器。发送带有数据的文件时,接收方会收到该文件中没有字节的空文件。与远程服务器的连接都很完美。 这是我的代码:

var stream;
stream = file.createReadStream(finalsrcFilename);
console.log("stream",stream);
stream.on("data", function(data) {
  console.log("data is",data.toString());
    chunk+= data.toString();
    console.log("chunk data",chunk);
}); 
stream.on('end',function(data){  
   console.log(data);
   console.log(chunk);
   sftp();
   //res.send("hello"); 
});  
stream.on('error', function(err){  
   console.log(err.stack);  
}); 
function sftp() {
let Client = require('ssh2-sftp-client');
let sftp = new Client();
var chunk = [];
const remotefilepath = 'xxxxxxxxxxxxx';
sftp.connect({
    host: 'xxxxxxxx.com',
    port: '22',
    username: 'xxxxxxxxxxx',
    password: 'xxxxxxxxxxx'

}).then(() => {
    console.log("stream",stream);
    return sftp.put(stream,remotefilepath);
}).then((data) => {
    console.log(data, 'the data info');
    res.send(data);
}).catch((err) => {
    console.log(err, 'catch error');
});

}

如果我将块变量放在流的位置(如return sftp.put(chunk,filename)),则出现错误,例如无法将数据上传到远程文件路径,并且ename太长。如果我放入流,那么当文件成功上传到远程文件路径时,它将返回200状态。但是在接收者端得到一个空文件。

1 个答案:

答案 0 :(得分:0)

  1. 最初在函数sftp()中,您声明流,但未分配任何数据,因此默认变量“ stream”为null,并且在上载时,将上载空值。
  2. 此处“块”是数据字符串,而不是文件名。因此,当您尝试提供“块”而不是“流”时,它会引发错误,因为stream.put方法将“块”作为文件名太长。

要处理此问题,请参阅下面的文章,其中解释了sftp到流中数据的远程传输。

Upload file from one API to other API in NodeJS

相关问题