Node中的SFTP模块下载和删除文件 [英] SFTP modules in Node to download and delete files
问题描述
我的任务(或者更好,应该)很简单:从 Node 应用程序中获取 SFTP 目录的内容,然后下载其中的所有文件,最后远程删除它们.
my task is (or better, should be) simple: to fetch the content of a directory in SFTP from a Node application, then download all the files in there and finally delete them remotely.
现在,我检查了不同的模块.在我看来,非常干净的是 ssh2-sftp-client.我可以这样使用它:
Now, I've checked different modules. Very clean, in my opinion, is ssh2-sftp-client. I can use it like this:
let Client = require('ssh2-sftp-client');
let sftp = new Client();
sftp.connect({
host: myhost,
port: '22',
username: myusername,
password: mypassword
}).then(() => {
return sftp.list('/path/to/my/files');
}).then((data) => {
for(var i = 0 ; i < data.length; i++) {
sftp.get('/path/to/my/files/'+data[i].name);
}
}).catch((err) => {
console.log(err, 'catch error');
});
我可以列出所有文件并在控制台中查看生成的 json,但是 .get 命令似乎什么也没做,我不知道出了什么问题.从文档(https://www.npmjs.com/package/ssh2-sftp-客户端)你可以像我一样简单地获取文件.但是:
I can list all files and see the resulting jSon in console, but the .get command seems to do nothing and I have no idea what is wrong. From the documentation (https://www.npmjs.com/package/ssh2-sftp-client) you can get files simply like I'm doing. But:
1) 它似乎不起作用2)我如何调试正在发生的事情?3)如果我没有机会选择本地目录,这些文件很可能会下载到node启动js的地方,对吗?
1) it doesn't seem to work 2) how can I debug what's going on? 3) if I have no chance to choose the local directory, will these files most probably be downloaded where the js is launched by node, right?
那么,如果使用此模块(或其他模块,如果有)成功下载文件,我如何才能实际下载并可能远程删除文件?
So, how could I get the files actually downloaded and possibly deleted remotely if they were successfully downloaded with this module (or others if any)?
谢谢,法比奥
推荐答案
sftp.get()
返回一个返回流的 Promise,所以如果你想将流保存到磁盘,你将需要管道它.例如:
sftp.get()
returns a Promise that returns a stream, so if you want to save the stream to disk, you will need to pipe it. For example:
var fs = require('fs');
// ...
for(var i = 0; i < data.length; i++) {
const remoteFilename = '/path/to/remote/files/' + data[i].name;
const localFilename = '/path/to/local/files/' + data[i].name;
sftp.get(remoteFilename).then((stream) => {
stream.pipe(fs.createWriteStream(localFilename));
});
}
此外,ssh2-sftp-client
似乎没有使用 ssh2
模块的最新版本分支(在撰写本文时为 v0.5.x),如果您遇到问题,请记住这一点.
Also, it appears that ssh2-sftp-client
is not using the latest version branch of the ssh2
module (v0.5.x as of this writing), so keep that in mind if you run into issues.
这篇关于Node中的SFTP模块下载和删除文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!