0
1

More than 1 year has passed since last update.

AzureStorage[Blob]をNodejsから操作する(ダウンロード)

Last updated at Posted at 2021-09-26

初めに

AzureのクラウドストレージであるAzureStorageBlob。
そのblobサービスのコンテナの中にある全てのファイルをローカルに環境に一括ダウンロードするためのプログラム(TypeScript)を紹介します。

環境

  • Node v14.17.0
  • Windows10
  • Typescript

コード

1ファイルで紹介したかったため1ファイルにすべて詰め込んでありますが、
適宜管理しやすいようにファイルを分けたほうがいいと思います。

package.json

package.json
{
  "name": "azurestorage",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "tsc && npm run main",
    "main": "node index.js",
    "clean": "tsc --build --clean"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@azure/arm-resources": "^4.2.0",
    "@azure/identity": "^1.3.0",
    "@azure/storage-blob": "^12.6.0",
    "@azure/storage-file-share": "^12.6.0"
  },
  "devDependencies": {
    "@types/node": "^15.12.2",
    "ts-node": "^10.0.0",
    "typescript": "^4.3.2"
  }
}

メインファイル

index.ts
import fs from 'fs'
import { BlobServiceClient, StorageSharedKeyCredential } from "@azure/storage-blob";

interface AzureStorageBlobConfig {
  type: 'SAS' | 'CONSTR' | 'KEY',
  connStr?: string,//CONSTR
  account?: string,//KEY,SAS
  accountKey?: string,//KEY
  sasToken?: string,
  containerName?: string[],
}

const AuthController = (authobj: AzureStorageBlobConfig) => {
  switch (authobj.type) {
    case 'SAS':
      if (authobj.account && authobj.sasToken) {
        return AuthSas(authobj.account, authobj.sasToken)
      } else {
        console.log(authobj.type + 'の認証情報が足りません')
      }
    case 'CONSTR':
      if (authobj.connStr) {
        return AuthConstr(authobj.connStr)
      } else {
        console.log(authobj.type + 'の認証情報が足りません')
      }
      break
    case 'KEY':
      if (authobj.account && authobj.accountKey) {
        return AuthKey(authobj.account, authobj.accountKey)
      } else {
        console.log(authobj.type + 'の認証情報が足りません')
      }
      break
  }
}

const AuthSas = (account: string, sastoken: string): BlobServiceClient => {
  return new BlobServiceClient(`https://${account}.blob.core.windows.net/${sastoken}`);
}

const AuthConstr = (connstr: string): BlobServiceClient => {
  return BlobServiceClient.fromConnectionString(connstr);
}

const AuthKey = (account: string, key: string) => {
  const sharedKeyCredential = new StorageSharedKeyCredential(account, key);
  return new BlobServiceClient(`https://${account}.blob.core.windows.net`, sharedKeyCredential);
}


//IIFE 即時関数
(async function main() {
  try {
    const authObj: AzureStorageBlobConfig = {
      type: 'CONSTR',
      connStr: "{your connection string}",
      containerName: ["{your containerNames}"]
    }

    let blobServiceClient = AuthController(authObj)

    if (blobServiceClient) {
      let containerNameList = []
      //get containerName
      if (authObj.containerName) {
        for (const container of authObj.containerName) {
          containerNameList.push(container)
        }
      } else {
        let containers = blobServiceClient.listContainers();
        for await (const container of containers) {
          containerNameList.push(container.name)
        }
      }
      //get BlobName
      Promise.all(containerNameList.map(async value => {
        if (blobServiceClient) {
          const containerClient = blobServiceClient.getContainerClient(value);
          for await (const blob of containerClient.listBlobsFlat()) {
            console.log(blob.name);
            const blobClient = containerClient.getBlobClient(blob.name);
            fs.mkdirSync(`./download/${value}/` + (path.dirname(blob.name).replace(/\.$/, '')), { recursive: true })
            await blobClient.downloadToFile(`./download/${value}/` + blob.name);
          }
        }
      }
      ))
    }
  } catch (e) {
    console.log(e)
  }
})()

使用方法

  1. npmのインストール

  2. メインファイルの即時関数と書いてあるあたりにあるauthObjに認証情報を入力する。
    認証タイプは接続文字列接続キーSASの3つから選ぶことが出来ます。
    コンテナ名を複数入力することで全てのコンテナ配下にあるファイルをダウンロードすることが出来ます。

  3. ダウンロードファイルの保存フォルダの確認
    (デフォルトではメインファイルの階層にdownloadフォルダが作成され、そこに保存されます)

  4. ダウンロードの実行npm start

終わりに

今回はAzureStorageのBlobダウンロードについて記事にしましたが、
FileSharedのダウンロードについても今後記事にする予定です。

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