다음을 통해 공유


Node.js에서 JavaScript SDK를 사용하여 Azure Data Lake Storage Gen2의 디렉터리 및 파일 관리

이 문서에서는 Node.js를 사용하여 계층 구조 네임스페이스가 있는 스토리지 계정에서 디렉터리 및 파일을 만들고 관리하는 방법을 보여 줍니다.

디렉터리 및 파일의 ACL(액세스 제어 목록)을 가져오거나 설정하고 업데이트하는 방법에 대한 자세한 내용은 Node.js에서 JavaScript SDK를 사용하여 Azure Data Lake Storage Gen2의 ACL 관리를 참조하세요.

패키지(노드 패키지 관리자) | 샘플 | 피드백 제공

필수 구성 요소

  • Azure 구독 자세한 내용은 Azure 무료 평가판 가져오기 를 참조하세요.

  • 계층 구조 네임스페이스가 사용하도록 설정된 스토리지 계정입니다. 이러한 지침에 따라 라이브러리를 만듭니다.

  • Node.js 애플리케이션에서 이 패키지를 사용 중인 경우 8.0.0 이상의 Node.js가 필요합니다.

프로젝트 설정

터미널 창을 열고 다음 명령을 입력하여 JavaScript용 Data Lake 클라이언트 라이브러리를 설치합니다.

npm install @azure/storage-file-datalake

이 명령문을 코드 파일의 맨 위에 배치하여 storage-file-datalake 패키지를 가져옵니다.

const {
AzureStorageDataLake,
DataLakeServiceClient,
StorageSharedKeyCredential
} = require("@azure/storage-file-datalake");

참고 항목

Data Lake Storage의 다중 프로토콜 액세스를 통해 애플리케이션은 Blob API와 Data Lake Storage Gen2 API를 모두 사용하여 HNS(계층 구조 네임스페이스)가 사용하도록 설정된 스토리지 계정의 데이터로 작업할 수 있습니다. 디렉터리 작업 및 ACL과 같은 Data Lake Storage Gen2의 고유한 기능을 사용하는 경우 이 문서에 표시된 대로 Data Lake Storage Gen2 API를 사용합니다.

특정 시나리오에서 사용할 API를 선택할 때 알려진 문제HNS가 워크로드 및 애플리케이션에 미치는 영향과 함께 애플리케이션의 워크로드와 요구 사항을 고려합니다.

계정에 연결

이 문서의 코드 조각을 사용하려면 스토리지 계정을 나타내는 DataLakeServiceClient 인스턴스를 만들어야 합니다.

Microsoft Entra ID를 사용한 연결

JS용 Azure ID 클라이언트 라이브러리를 사용하여 Microsoft Entra ID로 애플리케이션을 인증할 수 있습니다.

DataLakeServiceClient 인스턴스를 만들고 DefaultAzureCredential 클래스의 새 인스턴스를 전달합니다.

function GetDataLakeServiceClientAD(accountName) {

  const dataLakeServiceClient = new DataLakeServiceClient(
      `https://${accountName}.dfs.core.windows.net`,
      new DefaultAzureCredential());

  return dataLakeServiceClient;
}

DefaultAzureCredential을 사용하여 데이터에 대한 액세스 권한을 부여하는 방법에 대한 자세한 내용은 개요: Azure SDK를 사용하여 Azure에 JavaScript 앱 인증을 참조하세요.

계정 키를 사용하여 연결

계정 액세스 키(공유 키)를 사용하여 데이터에 대한 액세스 권한을 부여할 수 있습니다. 이 예제에서는 계정 키로 권한이 부여된 DataLakeServiceClient 인스턴스를 만듭니다.


function GetDataLakeServiceClient(accountName, accountKey) {

  const sharedKeyCredential =
     new StorageSharedKeyCredential(accountName, accountKey);

  const dataLakeServiceClient = new DataLakeServiceClient(
      `https://${accountName}.dfs.core.windows.net`, sharedKeyCredential);

  return dataLakeServiceClient;
}

이 권한 부여 방법은 Node.js 애플리케이션에만 적용됩니다. 브라우저에서 코드를 실행하려는 경우 Microsoft Entra ID를 사용하여 권한을 부여할 수 있습니다.

주의

공유 키를 사용한 권한 부여는 안전하지 않을 수 있어 권장하지 않습니다. 최적의 보안을 위해 Azure Storage 계정에 대한 공유 키 권한 부여 방지에 설명된 대로 스토리지 계정에 대해 공유 키를 통한 권한 부여를 비활성화합니다.

액세스 키 및 연결 문자열 사용은 프로덕션 또는 중요한 데이터에 액세스하지 않는 초기 개념 증명 앱 또는 개발 프로토타입으로 제한되어야 합니다. 그렇지 않으면 Azure 리소스에 인증할 때 Azure SDK에서 사용할 수 있는 토큰 기반 인증 클래스를 항상 기본으로 설정해야 합니다.

Microsoft에서는 클라이언트가 Microsoft Entra ID 또는 SAS(공유 액세스 서명)를 사용하여 Azure Storage의 데이터에 대한 액세스 권한을 부여하는 것이 좋습니다. 자세한 내용은 데이터 액세스에 대한 작업 권한 부여를 참조하세요.

컨테이너 만들기

컨테이너는 파일의 파일 시스템 역할을 합니다. FileSystemClient 인스턴스를 가져온 다음 FileSystemClient.Create 메서드를 호출하여 컨테이너를 만들 수 있습니다.

다음 예제에서는 my-file-system이라는 컨테이너를 만듭니다.

async function CreateFileSystem(dataLakeServiceClient) {

  const fileSystemName = "my-file-system";

  const fileSystemClient = dataLakeServiceClient.getFileSystemClient(fileSystemName);

  const createResponse = await fileSystemClient.create();

}

디렉터리 만들기

DirectoryClient 인스턴스를 가져온 다음 DirectoryClient.create 메서드를 호출하여 디렉터리 참조를 만듭니다.

이 예제에서는 my-directory라는 디렉터리를 컨테이너에 추가합니다.

async function CreateDirectory(fileSystemClient) {

  const directoryClient = fileSystemClient.getDirectoryClient("my-directory");

  await directoryClient.create();

}

디렉터리 이름 바꾸기 또는 이동

DirectoryClient.rename 메서드를 호출하여 디렉터리 이름을 바꾸거나 이동합니다. 원하는 디렉터리의 경로를 매개 변수로 전달합니다.

이 예제에서는 한 하위 디렉터리를 my-directory-renamed라는 이름으로 바꿉니다.

async function RenameDirectory(fileSystemClient) {

  const directoryClient = fileSystemClient.getDirectoryClient("my-directory");
  await directoryClient.move("my-directory-renamed");

}

이 예제에서는 my-directory-renamed라는 디렉터리를 my-directory-2라는 디렉터리의 하위 디렉터리로 이동합니다.

async function MoveDirectory(fileSystemClient) {

  const directoryClient = fileSystemClient.getDirectoryClient("my-directory-renamed");
  await directoryClient.move("my-directory-2/my-directory-renamed");

}

디렉터리 삭제

DirectoryClient.delete 메서드를 호출하여 디렉터리를 삭제합니다.

다음 예제에서는 my-directory라는 디렉터리를 삭제합니다.

async function DeleteDirectory(fileSystemClient) {

  const directoryClient = fileSystemClient.getDirectoryClient("my-directory");
  await directoryClient.delete();

}

디렉터리에 파일 업로드

먼저 파일을 읽습니다. 이 예제에서는 Node.js fs 모듈을 사용합니다. 그런 다음 FileClient 인스턴스를 만든 후 FileClient.create 메서드를 호출하여 대상 디렉터리에 파일 참조를 만듭니다. FileClient.append 메서드를 호출하여 파일을 업로드합니다. FileClient.flush 메서드를 호출하여 업로드를 완료해야 합니다.

다음 예제에서는 한 텍스트 파일을 my-directory라는 디렉터리에 업로드합니다.

async function UploadFile(fileSystemClient) {

  const fs = require('fs')

  var content = "";

  fs.readFile('mytestfile.txt', (err, data) => {
      if (err) throw err;

      content = data.toString();

  })

  const fileClient = fileSystemClient.getFileClient("my-directory/uploaded-file.txt");
  await fileClient.create();
  await fileClient.append(content, 0, content.length);
  await fileClient.flush(content.length);

}

디렉터리에서 다운로드

먼저, 다운로드하려는 파일을 나타내는 FileSystemClient 인스턴스를 만듭니다. FileSystemClient.read 메서드를 사용하여 파일을 읽습니다. 그런 다음 파일을 작성합니다. 이 예에서는 Node.js fs 모듈을 사용하여 해당 작업을 수행합니다.

참고 항목

이 파일 다운로드 방법은 Node.js 애플리케이션에만 적용됩니다. 브라우저에서 코드를 실행하려는 경우 JavaScript용 Azure Storage File Data Lake 클라이언트 라이브러리 추가 정보 파일에서 해당 방법의 예를 참조하세요.

async function DownloadFile(fileSystemClient) {

  const fileClient = fileSystemClient.getFileClient("my-directory/uploaded-file.txt");

  const downloadResponse = await fileClient.read();

  const downloaded = await streamToString(downloadResponse.readableStreamBody);

  async function streamToString(readableStream) {
    return new Promise((resolve, reject) => {
      const chunks = [];
      readableStream.on("data", (data) => {
        chunks.push(data.toString());
      });
      readableStream.on("end", () => {
        resolve(chunks.join(""));
      });
      readableStream.on("error", reject);
    });
  }

  const fs = require('fs');

  fs.writeFile('mytestfiledownloaded.txt', downloaded, (err) => {
    if (err) throw err;
  });
}

디렉터리 콘텐츠 나열

이 예제에서는 my-directory라는 디렉터리에 있는 각 디렉터리와 파일의 이름을 인쇄합니다.

async function ListFilesInDirectory(fileSystemClient) {

  let i = 1;

  let iter = await fileSystemClient.listPaths({path: "my-directory", recursive: true});

  for await (const path of iter) {

    console.log(`Path ${i++}: ${path.name}, is directory: ${path.isDirectory}`);
  }

}

참고 항목