Share via


JavaScript용 Azure Storage Blob 클라이언트 라이브러리 - 버전 12.18.0

Azure Storage Blob은 클라우드용 Microsoft의 개체 스토리지 솔루션입니다. Blob Storage는 구조화되지 않은 대량의 데이터를 저장하는 데 최적화되어 있습니다. 비정형 데이터는 특정 데이터 모델이나 정의를 따르지 않는, 텍스트 또는 이진 데이터와 같은 데이터입니다.

이 프로젝트는 Microsoft Azure Storage Blob 서비스를 쉽게 사용할 수 있는 JavaScript의 클라이언트 라이브러리를 제공합니다.

이 패키지의 클라이언트 라이브러리를 사용하여 다음을 수행합니다.

  • Blob 서비스 속성 가져오기/설정
  • 컨테이너 Create/나열/삭제
  • 블록 Blob Create/읽기/나열/업데이트/삭제
  • Create/읽기/목록/업데이트/페이지 Blob 삭제
  • Create/읽기/나열/업데이트/추가 Blob 삭제

키 링크

시작

현재 지원되는 환경

자세한 내용은 지원 정책을 참조하세요.

필수 구성 요소

패키지 설치

JavaScript용 Azure Storage Blob 클라이언트 라이브러리를 설치하는 기본 방법은 npm 패키지 관리자를 사용하는 것입니다. 터미널 창에 다음을 입력합니다.

npm install @azure/storage-blob

클라이언트 인증

Azure Storage는 인증하는 여러 가지 방법을 지원합니다. Azure Blob Storage 서비스와 상호 작용하려면 스토리지 클라이언트BlobServiceClient의 instance 만들어야 합니다( , ContainerClient또는 BlobClient ). 인증에 대한 자세한 내용은 를 만들기 BlobServiceClient위한 샘플을 참조하세요.

Azure Active Directory

Azure Blob Storage 서비스는 Azure Active Directory를 사용하여 해당 API에 대한 요청을 인증할 수 있도록 지원합니다. 패키지는 @azure/identity 애플리케이션에서 이 작업을 수행하는 데 사용할 수 있는 다양한 자격 증명 형식을 제공합니다. 시작하기 위한 @azure/identity 자세한 내용 및 샘플은 추가 정보를 참조하세요.

호환성

이 라이브러리는 Node.js 및 브라우저와 호환되며 LTS Node.js 버전(>=8.16.0) 및 최신 버전의 Chrome, Firefox 및 Edge에 대해 유효성을 검사합니다.

웹 작업자

이 라이브러리를 사용하려면 웹 작업자가 기본적으로 사용할 수 없는 브라우저에서 사용할 때 특정 DOM 개체를 전역적으로 사용할 수 있어야 합니다. 이 라이브러리가 웹 작업자에서 작동하도록 하려면 이러한 라이브러리를 폴리필해야 합니다.

자세한 내용은 웹 작업자에서 JS용 Azure SDK 사용에 대한 설명서를 참조하세요.

이 라이브러리는 웹 작업자에서 사용할 때 로드된 외부 폴리필이 필요한 다음 DOM API에 따라 달라집니다.

Node.js 브라우저 간의 차이점

Node.js 브라우저 런타임 간에는 차이가 있습니다. 이 라이브러리를 시작할 때 "NODE.JS 런타임에서만 사용 가능" 또는 "브라우저에서만 사용 가능"으로 표시된 API 또는 클래스에 주의 하세요.

  • Blob이 압축된 데이터를 또는 deflate 형식으로 gzip 보유하고 콘텐츠 인코딩이 그에 따라 설정된 경우 다운로드 동작은 Node.js 브라우저 간에 다릅니다. Node.js 스토리지 클라이언트는 압축된 형식으로 Blob을 다운로드하고 브라우저에서는 데이터가 압축 해제된 형식으로 다운로드됩니다.
기능, 인터페이스, 클래스 또는 함수는 Node.js
  • 계정 이름 및 계정 키를 기반으로 하는 공유 키 권한 부여
    • StorageSharedKeyCredential
  • SAS(공유 액세스 서명) 생성
    • generateAccountSASQueryParameters()
    • generateBlobSASQueryParameters()
  • 병렬 업로드 및 다운로드. BlockBlobClient.uploadData()Node.js 브라우저에서 모두 사용할 수 있습니다.
    • BlockBlobClient.uploadFile()
    • BlockBlobClient.uploadStream()
    • BlobClient.downloadToBuffer()
    • BlobClient.downloadToFile()
브라우저에서만 사용할 수 있는 기능, 인터페이스, 클래스 또는 함수
  • 병렬 업로드 및 다운로드
    • BlockBlobClient.uploadBrowserData()

JavaScript 번들

브라우저에서 이 클라이언트 라이브러리를 사용하려면 먼저 번들러를 사용해야 합니다. 이 작업을 수행하는 방법에 대한 자세한 내용은 번들링 설명서를 참조하세요.

CORS

브라우저용으로 개발해야 하는 경우 스토리지 계정에 대해 CORS(원본 간 리소스 공유) 규칙을 설정해야 합니다. Azure Portal 이동하여 Azure Storage Explorer 스토리지 계정을 찾고 Blob/queue/file/table service에 대한 새 CORS 규칙을 만듭니다.

예를 들어 디버깅을 위해 다음 CORS 설정을 만들 수 있습니다. 하지만 프로덕션 환경의 요구 사항에 따라 설정을 신중하게 사용자 지정하세요.

  • 허용된 원본: *
  • 허용되는 동사: DELETE, GET,HEAD,MERGE,POST,OPTIONS,PUT
  • 허용되는 헤더: *
  • 노출된 헤더: *
  • 최대 연령(초): 86400

주요 개념

Blob Storage는 다음을 위해 설계되었습니다.

  • 브라우저에 이미지 또는 문서 직접 제공
  • 분산 액세스용 파일 저장.
  • 비디오 및 오디오 스트리밍.
  • 로그 파일에 쓰기
  • 백업/복원, 재해 복구 및 보관용 데이터 저장
  • 온-프레미스 또는 Azure 호스팅 서비스에서 분석하기 위한 데이터 저장.

Blob Storage는 다음 세 가지 유형의 리소스를 제공합니다.

  • 를 통해 사용되는 스토리지 계정BlobServiceClient
  • 를 통해 사용되는 스토리지 계정의 컨테이너ContainerClient
  • 를 통해 사용되는 컨테이너의 BlobBlobClient

예제

패키지 가져오기

클라이언트를 사용하려면 패키지를 파일로 가져옵니다.

const AzureStorageBlob = require("@azure/storage-blob");

또는 필요한 형식만 선택적으로 가져옵니다.

const { BlobServiceClient, StorageSharedKeyCredential } = require("@azure/storage-blob");

Blob 서비스 클라이언트 Create

BlobServiceClient 에는 Blob 서비스에 대한 URL과 액세스 자격 증명이 필요합니다. 또한 필요에 따라 매개 변수의 일부 설정을 options 허용합니다.

with DefaultAzureCredential from @azure/identity package

를 인스턴스화하는 권장 방법 BlobServiceClient

설치: 참조 - 클라이언트 애플리케이션에서 Azure Active Directory를 사용하여 Blob 및 큐에 대한 액세스 권한 부여 - /azure/storage/common/storage-auth-aad-app

  • 새 AAD 애플리케이션을 등록하고 로그인한 사용자를 대신하여 Azure Storage에 액세스할 수 있는 권한을 부여합니다.

    • Azure Active Directory(azure-portal)에 새 애플리케이션 등록 - /azure/active-directory/develop/quickstart-register-app
    • API permissions 섹션에서 를 선택하고 Add a permission 선택합니다Microsoft APIs.
    • 옆에 있는 확인란을 user_impersonation 선택하고 Azure Storage 선택한 다음 을 클릭합니다Add permissions. 이렇게 하면 애플리케이션이 로그인한 사용자를 대신하여 Azure Storage에 액세스할 수 있습니다.
  • Azure Portal에서 RBAC를 사용하여 Azure Blob 데이터에 대한 액세스 권한 부여

    • Blob 및 큐에 대한 RBAC 역할 - /azure/storage/common/storage-auth-aad-rbac-portal.
    • Azure Portal에서 스토리지 계정으로 이동하여 탭에서 Access control (IAM) 등록된 AAD 애플리케이션에 Storage Blob 데이터 기여자 역할을 할당합니다(azure-portal에 있는 스토리지 계정의 왼쪽 탐색 모음).
  • 샘플에 대한 환경 설정

    • AAD 애플리케이션의 개요 페이지에서 및 TENANT IDCLIENT ID 적어둡니다. "인증서 & 비밀" 탭에서 비밀을 만들고 아래로 기록해 둡니다.
    • 샘플을 성공적으로 실행하기 위한 환경 변수로 AZURE_TENANT_ID, AZURE_CLIENT_ID AZURE_CLIENT_SECRET 있는지 확인합니다(process.env를 활용할 수 있습니다).
const { DefaultAzureCredential } = require("@azure/identity");
const { BlobServiceClient } = require("@azure/storage-blob");

// Enter your storage account name
const account = "<account>";
const defaultAzureCredential = new DefaultAzureCredential();

const blobServiceClient = new BlobServiceClient(
  `https://${account}.blob.core.windows.net`,
  defaultAzureCredential
);

이 메서드를 사용하는 전체 예제는 Azure AD 인증 샘플을 참조하세요.

[참고 - 위의 단계는 Node.js 전용입니다.]

연결 문자열 사용

또는 전체 연결 문자열 인수로 fromConnectionString() 정적 메서드를 사용하여 를 인스턴스화 BlobServiceClient 할 수 있습니다. (연결 문자열 azure Portal에서 가져올 수 있습니다.) [NODE.JS 런타임에서만 사용 가능]

const { BlobServiceClient } = require("@azure/storage-blob");

const connStr = "<connection string>";

const blobServiceClient = BlobServiceClient.fromConnectionString(connStr);

을 사용하여 StorageSharedKeyCredential

또는 account-name 및 account-key를 BlobServiceClient 인수로 전달하여 를 StorageSharedKeyCredential 사용하여 를 인스턴스화합니다. (계정 이름 및 계정 키는 Azure Portal에서 가져올 수 있습니다.) [NODE.JS 런타임에서만 사용 가능]

const { BlobServiceClient, StorageSharedKeyCredential } = require("@azure/storage-blob");

// Enter your storage account name and shared key
const account = "<account>";
const accountKey = "<accountkey>";

// Use StorageSharedKeyCredential with storage account and account key
// StorageSharedKeyCredential is only available in Node.js runtime, not in browsers
const sharedKeyCredential = new StorageSharedKeyCredential(account, accountKey);
const blobServiceClient = new BlobServiceClient(
  `https://${account}.blob.core.windows.net`,
  sharedKeyCredential
);

SAS 토큰으로

또한 SAS(공유 액세스 서명)를 사용하여 를 인스턴스화 BlobServiceClient 할 수 있습니다. Azure Portal에서 SAS 토큰을 얻거나 를 사용하여 generateAccountSASQueryParameters()생성할 수 있습니다.

const { BlobServiceClient } = require("@azure/storage-blob");

const account = "<account name>";
const sas = "<service Shared Access Signature Token>";

const blobServiceClient = new BlobServiceClient(`https://${account}.blob.core.windows.net${sas}`);

새 컨테이너 만들기

를 사용하여 BlobServiceClient.getContainerClient() 컨테이너 클라이언트를 instance 다음, 새 컨테이너 리소스를 만듭니다.

const { DefaultAzureCredential } = require("@azure/identity");
const { BlobServiceClient } = require("@azure/storage-blob");

const account = "<account>";
const defaultAzureCredential = new DefaultAzureCredential();

const blobServiceClient = new BlobServiceClient(
  `https://${account}.blob.core.windows.net`,
  defaultAzureCredential
);

async function main() {
  // Create a container
  const containerName = `newcontainer${new Date().getTime()}`;
  const containerClient = blobServiceClient.getContainerClient(containerName);
  const createContainerResponse = await containerClient.create();
  console.log(`Create container ${containerName} successfully`, createContainerResponse.requestId);
}

main();

컨테이너 나열

함수를 사용하여 BlobServiceClient.listContainers()for-await-of 구문을 사용하여 컨테이너를 반복합니다.

const { DefaultAzureCredential } = require("@azure/identity");
const { BlobServiceClient } = require("@azure/storage-blob");

const account = "<account>";
const defaultAzureCredential = new DefaultAzureCredential();

const blobServiceClient = new BlobServiceClient(
  `https://${account}.blob.core.windows.net`,
  defaultAzureCredential
);

async function main() {
  let i = 1;
  let containers = blobServiceClient.listContainers();
  for await (const container of containers) {
    console.log(`Container ${i++}: ${container.name}`);
  }
}

main();

또는 를 사용하지 for-await-of않고:

const { DefaultAzureCredential } = require("@azure/identity");
const { BlobServiceClient } = require("@azure/storage-blob");

const account = "<account>";
const defaultAzureCredential = new DefaultAzureCredential();

const blobServiceClient = new BlobServiceClient(
  `https://${account}.blob.core.windows.net`,
  defaultAzureCredential
);

async function main() {
  let i = 1;
  let iter = blobServiceClient.listContainers();
  let containerItem = await iter.next();
  while (!containerItem.done) {
    console.log(`Container ${i++}: ${containerItem.value.name}`);
    containerItem = await iter.next();
  }
}

main();

또한 페이지를 매긴 항목은 을 통해서도 나열할 수 byPage()있습니다.

const { DefaultAzureCredential } = require("@azure/identity");
const { BlobServiceClient } = require("@azure/storage-blob");

const account = "<account>";
const defaultAzureCredential = new DefaultAzureCredential();

const blobServiceClient = new BlobServiceClient(
  `https://${account}.blob.core.windows.net`,
  defaultAzureCredential
);

async function main() {
  let i = 1;
  for await (const response of blobServiceClient.listContainers().byPage({ maxPageSize: 20 })) {
    if (response.containerItems) {
      for (const container of response.containerItems) {
        console.log(`Container ${i++}: ${container.name}`);
      }
    }
  }
}

main();

반복 컨테이너에 대한 전체 샘플은 samples/v12/typescript/src/listContainers.ts 참조하세요.

데이터를 업로드하여 Blob Create

const { DefaultAzureCredential } = require("@azure/identity");
const { BlobServiceClient } = require("@azure/storage-blob");

const account = "<account>";
const defaultAzureCredential = new DefaultAzureCredential();

const blobServiceClient = new BlobServiceClient(
  `https://${account}.blob.core.windows.net`,
  defaultAzureCredential
);

const containerName = "<container name>";

async function main() {
  const containerClient = blobServiceClient.getContainerClient(containerName);

  const content = "Hello world!";
  const blobName = "newblob" + new Date().getTime();
  const blockBlobClient = containerClient.getBlockBlobClient(blobName);
  const uploadBlobResponse = await blockBlobClient.upload(content, content.length);
  console.log(`Upload block blob ${blobName} successfully`, uploadBlobResponse.requestId);
}

main();

컨테이너 내의 Blob 나열

컨테이너 나열과 유사합니다.

const { DefaultAzureCredential } = require("@azure/identity");
const { BlobServiceClient } = require("@azure/storage-blob");

const account = "<account>";
const defaultAzureCredential = new DefaultAzureCredential();

const blobServiceClient = new BlobServiceClient(
  `https://${account}.blob.core.windows.net`,
  defaultAzureCredential
);

const containerName = "<container name>";

async function main() {
  const containerClient = blobServiceClient.getContainerClient(containerName);

  let i = 1;
  let blobs = containerClient.listBlobsFlat();
  for await (const blob of blobs) {
    console.log(`Blob ${i++}: ${blob.name}`);
  }
}

main();

Blob 반복에 대한 전체 샘플은 samples/v12/typescript/src/listBlobsFlat.ts 참조하세요.

Blob을 다운로드하고 문자열로 변환(Node.js)

const { DefaultAzureCredential } = require("@azure/identity");
const { BlobServiceClient } = require("@azure/storage-blob");

const account = "<account>";
const defaultAzureCredential = new DefaultAzureCredential();

const blobServiceClient = new BlobServiceClient(
  `https://${account}.blob.core.windows.net`,
  defaultAzureCredential
);

const containerName = "<container name>";
const blobName = "<blob name>";

async function main() {
  const containerClient = blobServiceClient.getContainerClient(containerName);
  const blobClient = containerClient.getBlobClient(blobName);

  // Get blob content from position 0 to the end
  // In Node.js, get downloaded data by accessing downloadBlockBlobResponse.readableStreamBody
  const downloadBlockBlobResponse = await blobClient.download();
  const downloaded = (
    await streamToBuffer(downloadBlockBlobResponse.readableStreamBody)
  ).toString();
  console.log("Downloaded blob content:", downloaded);

  // [Node.js only] A helper method used to read a Node.js readable stream into a Buffer
  async function streamToBuffer(readableStream) {
    return new Promise((resolve, reject) => {
      const chunks = [];
      readableStream.on("data", (data) => {
        chunks.push(data instanceof Buffer ? data : Buffer.from(data));
      });
      readableStream.on("end", () => {
        resolve(Buffer.concat(chunks));
      });
      readableStream.on("error", reject);
    });
  }
}

main();

Blob을 다운로드하고 문자열(브라우저)로 변환합니다.

브라우저에서 이 라이브러리를 사용하는 방법에 대한 자세한 내용은 JavaScript 번들 섹션을 참조하세요.

const { BlobServiceClient } = require("@azure/storage-blob");

const account = "<account name>";
const sas = "<service Shared Access Signature Token>";
const containerName = "<container name>";
const blobName = "<blob name>";

const blobServiceClient = new BlobServiceClient(`https://${account}.blob.core.windows.net${sas}`);

async function main() {
  const containerClient = blobServiceClient.getContainerClient(containerName);
  const blobClient = containerClient.getBlobClient(blobName);

  // Get blob content from position 0 to the end
  // In browsers, get downloaded data by accessing downloadBlockBlobResponse.blobBody
  const downloadBlockBlobResponse = await blobClient.download();
  const downloaded = await blobToString(await downloadBlockBlobResponse.blobBody);
  console.log("Downloaded blob content", downloaded);

  // [Browsers only] A helper method used to convert a browser Blob into string.
  async function blobToString(blob) {
    const fileReader = new FileReader();
    return new Promise((resolve, reject) => {
      fileReader.onloadend = (ev) => {
        resolve(ev.target.result);
      };
      fileReader.onerror = reject;
      fileReader.readAsText(blob);
    });
  }
}

main();

간단한 시나리오의 전체 예는 samples/v12/typescript/src/sharedKeyAuth.ts.

문제 해결

로깅을 사용하도록 설정하면 실패에 대한 유용한 정보를 파악하는 데 도움이 될 수 있습니다. HTTP 요청 및 응답 로그를 보려면 AZURE_LOG_LEVEL 환경 변수를 info로 설정합니다. 또는 @azure/logger에서 setLogLevel을 호출하여 런타임에 로깅을 사용하도록 설정할 수 있습니다.

const { setLogLevel } = require("@azure/logger");

setLogLevel("info");

다음 단계

추가 코드 샘플:

참여

이 라이브러리에 기여하려면 기여 가이드 를 참조하여 코드를 빌드하고 테스트하는 방법에 대해 자세히 알아보세요.

또한 스토리지 라이브러리에 대한 테스트 환경 설정에 대한 자세한 내용은 스토리지 관련 가이드 를 참조하세요.

Impressions