LoginSignup
1
1

More than 5 years have passed since last update.

node.jsでサイトからリスト一覧の画像をダウンロードする

Last updated at Posted at 2019-03-12

いきさつ

とあるwordpress案件で、古いサーバーから記事に使っている画像データを、
ディレクトリ構造を保持したままダウンロードしたかった。
しかし、アクセス権は与えられなかったので、web経由で落とすしかなかった。

Node.jsでなんとか出来ないだろうか。
出来た。

とりあえず、画像のパス一覧の配列を用意する

これは、どうにかして用意してください。
僕の場合はエクスポートしたデータのxmlから、正規表現でなんとか抽出して作りました。

script.js
  // 画像のルート相対パス
const urls = [
  '/wordpress/wp-content/uploads/2017/03/aaa.png',
  '/wordpress/wp-content/uploads/2018/06/bbb.png',
  '/wordpress/wp-content/uploads/2019/04/ccc.png'
];

node.js用のスクリプトを書く

script.js
// node -v v10.13.0
const fs = require('fs');
const path = require('path');
const request = require('request');
const async = require('async');

const domain = 'http://hogehoge.jp'; // ダウンロードしたいサイトのURL

const urls = [ // 画像のルート相対パス
  '/wordpress/wp-content/uploads/2017/03/aaa.png',
  '/wordpress/wp-content/uploads/2018/06/bbb.png',
  '/wordpress/wp-content/uploads/2019/04/ccc.png'
];

async.each(urls, (data, next) => { // 同期処理でリストを回す
  const options = {
    url: encodeURI(domain + data), // 日本語のファイル名だとエラーになるのでエンコード
    method: 'GET',
    encoding: null
  };
  request(options, function(error, response, body) {
    if (!error && response.statusCode === 200) {
      // mkdirSyncの「recursive: true」オプションでディレクトリを再帰的に作ってくれる
      fs.mkdirSync(path.dirname(__dirname + data), { recursive: true }, err => {
        if (err) throw err;
      });
      fs.writeFileSync(__dirname + data, body, 'binary'); // 画像をダウンロード
    }
  });
});

node script.js

これを nodeで実行すれば、カレントディレクトリに階層が保持されたままのファイルがダウンロードされている。

注意

多用するとサーバーに負荷をかけるので、
案件で必要です、って時以外は使わないようにしてください。

1
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
1
1