3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Node.jsでFTP通信しディレクトリごとダウンロードする

Last updated at Posted at 2016-11-29

概要

Node.jsでFTP通信し、ディレクトリごとダウンロードする方法について記す。

基本的には
http://qiita.com/PianoScoreJP/items/2ae8a293b3445d8d1cdf
に記されてる通り。

https://www.npmjs.com/package/ftp-client でmultiple downloadについてあるが、何故かファイルがディレクトリごとに一つずつスキップされる。不安定

方法

※結論として頑張る方法が1番よい

var fs = require('fs');
var client = require('ftp');

var c = new client();
c.connect({
    host:"ftp.hoge.com",
    port:21,//portが21の場合は省略可能
    user:"youraccount",
    password:"yourpassword"
})

c.on('ready', function() {

  console.log('start donwload');

  // ローカルにディレクトリあるか確認・なければ作る
  var dir = 'Sample';
  if (!fs.existsSync(dir)){
    fs.mkdirSync(dir);
  }

  // リモートの対象ディレクトリ内のファイルを根こそぎダウンロード
  c.cwd('Sample',function(err, currentDir) {
    if (err) throw err;
    c.list(function(err,list){
      list.forEach(function(element, index) {
        c.get(element.name, function(err, stream) {
          if (err) throw err;
          console.log(index + ":" + element.name);
          stream.once('close', function() {
            console.log('finish 1 file');
          });
          stream.pipe(fs.createWriteStream('Sample/' + element.name));
        });
      });
    });
  });
  c.end();
});

// 何か処理をしたい場合はコールバックを使う
c.on('end',function(){
  console.log('finish donwload');
});

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?