샌드박스에서 파일 읽어 내기

샌드박스에서 파일 읽어 내기

빌드 결과를 읽거나, 프로젝트 파일을 검사하거나, 샌드박스를 삭제하기 전에 데이터를 복사해 봐요. 실행 중인 샌드박스 핸들과 그 안의 절대 경로로 시작하세요.

출처: 문서

본문

예시는 콘텐츠를 애플리케이션으로 반환해요. 머신에 보관하려면 받은 바이트를 로컬 파일에 쓰세요.

디렉터리 나열

파일 컬렉션의 반복자로 디렉터리를 순회해요. 페이지 매김을 따르고 항목을 반환해요. 나열은 메타데이터를 주지, 파일 콘텐츠를 주지 않아요.

핵심 코드:

return sandbox.files.all(path).collect();

완전한 TypeScript 예시: download/list.ts

import type { Sandbox } from '@docker/sandboxes';

export async function listDirectory(sandbox: Sandbox, path: string) {
  return sandbox.files.all(path).collect();
}

작은 텍스트 파일 읽기

메모리에 두고 싶은 텍스트에는 경계 있는 읽기 헬퍼(bounded read helper)를 사용하세요. 예시는 읽기를 1 MiB로 제한해요. 애플리케이션의 메모리 예산에 맞는 경계를 선택하거나 더 큰 파일은 스트림으로 다운로드하세요.

핵심 코드:

return sandbox.files.read(path, {
  encoding: 'utf8',
  maxBytes: 1024 * 1024,
});

완전한 TypeScript 예시: download/read.ts

import type { Sandbox } from '@docker/sandboxes';

export async function readFile(sandbox: Sandbox, path: string) {
  return sandbox.files.read(path, {
    encoding: 'utf8',
    maxBytes: 1024 * 1024,
  });
}

경로 검사

다운로드, 이동, 제거 여부를 결정하기 전에 메타데이터를 읽어요. 성공적인 메타데이터 읽기는 파일을 예약하지 않아요. 다른 프로세스가 이후에 변경할 수 있어요.

핵심 코드:

return sandbox.files.stat(path);

완전한 TypeScript 예시: download/stat.ts

import type { Sandbox } from '@docker/sandboxes';

export async function statFile(sandbox: Sandbox, path: string) {
  return sandbox.files.stat(path);
}

파일을 스트림으로 다운로드

샌드박스 경로와 바이트를 소비하는 콜백이나 라이터를 전달하세요. 예시는 끝나거나 실패하면 전송을 닫아요.

다운로드가 성공적으로 끝났을 때만 완료로 취급하세요. 중간에 실패하면 재시도하기 전에 부분 로컬 파일을 폐기하거나 별도로 식별하세요.

핵심 코드:

const download = await sandbox.files.download(path);
try {
  for await (const chunk of download) write(chunk);
} finally {
  await download.close();
}

완전한 TypeScript 예시: download/download.ts

import type { Sandbox } from '@docker/sandboxes';

export async function downloadFiles(
  sandbox: Sandbox,
  path: string,
  write: (bytes: Uint8Array) => void,
) {
  const download = await sandbox.files.download(path);
  try {
    for await (const chunk of download) write(chunk);
  } finally {
    await download.close();
  }
}

경로 이동

현재 경로와 대상을 전달하세요. 이는 샌드박스 안에서 데이터를 이동하지, 컴퓨터로 아무것도 다운로드하지 않아요.

핵심 코드:

await sandbox.files.move(from, to);

완전한 TypeScript 예시: download/move.ts

import type { Sandbox } from '@docker/sandboxes';

export async function movePath(
  sandbox: Sandbox,
  from: string,
  to: string,
) {
  await sandbox.files.move(from, to);
}

경로 제거

파일을 제거하거나 디렉터리 트리를 위해 재귀적 제거를 활성화해요. 요청한 제거가 모두 성공했다고 가정하지 말고 실패한 경로가 있는지 결과를 확인하세요.

재귀적 제거는 파괴적이에요. 사용자가 제공한 경로를 애플리케이션이 소유한 디렉터리에 한정하세요.

핵심 코드:

const result = await sandbox.files.remove(path, { recursive });
if (result.failedPath)
  throw new Error(`Remove ${path} stopped at ${result.failedPath}`);

완전한 TypeScript 예시: download/remove.ts

import type { Sandbox } from '@docker/sandboxes';

export async function removePath(
  sandbox: Sandbox,
  path: string,
  recursive: boolean,
) {
  const result = await sandbox.files.remove(path, { recursive });
  if (result.failedPath)
    throw new Error(`Remove ${path} stopped at ${result.failedPath}`);
}

더 알아보기 (Learn more)