본문으로 건너뛰기
cccskills
무료GitHub에 공개

bun-file-io

Use for Bun file I/O: Bun.file, Bun.write, streams, directories, glob patterns, metadata.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

설치 방법 보기

포함된 파일(1)

  • SKILL.md7.5 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

Bun File I/O

Bun provides fast, optimized file operations via Bun.file() and Bun.write().

Reading Files

Bun.file()

// Create file reference (lazy, doesn't read yet)
const file = Bun.file("./data.txt");

// File properties
console.log(file.size);        // Size in bytes
console.log(file.type);        // MIME type
console.log(file.name);        // File path
console.log(await file.exists()); // Boolean

// Read content
const text = await file.text();
const json = await file.json();
const buffer = await file.arrayBuffer();
const bytes = await file.bytes();   // Uint8Array
const stream = file.stream();       // ReadableStream

Read Specific Types

// JSON file
const config = await Bun.file("config.json").json();

// Text file
const content = await Bun.file("readme.md").text();

// Binary file
const binary = await Bun.file("image.png").arrayBuffer();

// With import attributes
import data from "./data.json" with { type: "json" };
import text from "./content.txt" with { type: "text" };

Writing Files

Bun.write()

// Write string
await Bun.write("./output.txt", "Hello World");

// Write JSON
await Bun.write("./data.json", JSON.stringify({ key: "value" }, null, 2));

// Write binary
await Bun.write("./output.bin", new Uint8Array([1, 2, 3]));

// Write from Response
const response = await fetch("https://example.com/image.png");
await Bun.write("./image.png", response);

// Write from another file (efficient copy)
await Bun.write("./copy.txt", Bun.file("./original.txt"));

// Write with options
await Bun.write("./file.txt", "content", {
  mode: 0o644,  // Unix permissions
});

Appending

// Using Bun.file writer
const file = Bun.file("./log.txt");
const writer = file.writer();

writer.write("Line 1\n");
writer.write("Line 2\n");
await writer.flush();
writer.end();

// Or use node:fs
import { appendFile } from "node:fs/promises";
await appendFile("./log.txt", "New line\n");

Streaming

Read Stream

const file = Bun.file("./large-file.txt");
const stream = file.stream();

const reader = stream.getReader();
while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  // Process chunk (Uint8Array)
  console.log(value);
}

Write Stream

const file = Bun.file("./output.txt");
const writer = file.writer();

for await (const chunk of dataSource) {
  writer.write(chunk);
}

await writer.end();

Pipe Streams

// File to file
const input = Bun.file("./input.txt");
const output = Bun.file("./output.txt");
await Bun.write(output, input);

// HTTP response to file
const response = await fetch(url);
await Bun.write("./download.zip", response);

// Process stream
const file = Bun.file("./data.txt");
const stream = file.stream();

const transformed = stream.pipeThrough(
  new TransformStream({
    transform(chunk, controller) {
      // Process chunk
      controller.enqueue(chunk.toUpperCase());
    },
  })
);

Directory Operations

import { readdir, mkdir, rmdir, stat } from "node:fs/promises";
import { existsSync, mkdirSync } from "node:fs";

// List directory
const files = await readdir("./src");
const filesWithTypes = await readdir("./src", { withFileTypes: true });

for (const entry of filesWithTypes) {
  if (entry.isDirectory()) {
    console.log(`Dir: ${entry.name}`);
  } else if (entry.isFile()) {
    console.log(`File: ${entry.name}`);
  }
}

// Create directory
await mkdir("./new-dir", { recursive: true });

// Remove directory
await rmdir("./old-dir", { recursive: true });

// Check if exists
const exists = existsSync("./path");

Glob Patterns

// Using Bun.Glob
const glob = new Bun.Glob("**/*.ts");

// Scan directory
for await (const file of glob.scan({ cwd: "./src" })) {
  console.log(file); // Relative paths
}

// Get all matches
const files = await Array.fromAsync(glob.scan("./src"));

// With options
const glob2 = new Bun.Glob("**/*.{ts,tsx}");
for await (const file of glob2.scan({
  cwd: "./src",
  dot: true,           // Include dotfiles
  absolute: true,      // Return absolute paths
  onlyFiles: true,     // Only files, not directories
})) {
  console.log(file);
}

// Test if path matches
const pattern = new Bun.Glob("*.ts");
pattern.match("file.ts");    // true
pattern.match("file.js");    // false

File Metadata

import { stat, lstat } from "node:fs/promises";

const stats = await stat("./file.txt");

console.log(stats.size);          // Size in bytes
console.log(stats.isFile());      // Is regular file
console.log(stats.isDirectory()); // Is directory
console.log(stats.isSymbolicLink()); // Is symlink
console.log(stats.mtime);         // Modified time
console.log(stats.ctime);         // Changed time
console.log(stats.atime);         // Access time
console.log(stats.mode);          // Permissions

Path Operations

import { join, dirname, basename, extname, resolve } from "node:path";

const filePath = "/home/user/project/src/index.ts";

join("a", "b", "c");           // "a/b/c"
dirname(filePath);             // "/home/user/project/src"
basename(filePath);            // "index.ts"
basename(filePath, ".ts");     // "index"
extname(filePath);             // ".ts"
resolve("./relative");         // Absolute path

// Bun-specific
import.meta.dir;   // Directory of current file
import.meta.file;  // Filename
import.meta.path;  // Full path

Common Patterns

Read JSON Config

async function loadConfig<T>(path: string): Promise<T> {
  const file = Bun.file(path);
  if (!(await file.exists())) {
    throw new Error(`Config not found: ${path}`);
  }
  return file.json();
}

const config = await loadConfig<AppConfig>("./config.json");

Copy Directory

import { readdir, mkdir, stat } from "node:fs/promises";
import { join } from "node:path";

async function copyDir(src: string, dest: string) {
  await mkdir(dest, { recursive: true });

  for (const entry of await readdir(src, { withFileTypes: true })) {
    const srcPath = join(src, entry.name);
    const destPath = join(dest, entry.name);

    if (entry.isDirectory()) {
      await copyDir(srcPath, destPath);
    } else {
      await Bun.write(destPath, Bun.file(srcPath));
    }
  }
}

Watch Files

import { watch } from "node:fs";

watch("./src", { recursive: true }, (event, filename) => {
  console.log(`${event}: ${filename}`);
});

// Or with Bun's built-in (faster)
const watcher = Bun.spawn(["bun", "--watch", "src/index.ts"]);

Temp Files

import { mkdtemp } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";

// Create temp directory
const tempDir = await mkdtemp(join(tmpdir(), "app-"));
console.log(tempDir); // /tmp/app-xxxxx

// Write temp file
const tempFile = join(tempDir, "data.txt");
await Bun.write(tempFile, "temporary data");

Common Errors

ErrorCauseFix
ENOENTFile not foundCheck path, use exists()
EACCESPermission deniedCheck file permissions
EISDIRIs a directoryUse readdir() for directories
EEXISTAlready existsUse recursive: true for mkdir

When to Load References

Load references/streams-advanced.md when:

  • Transform streams
  • Compression streams
  • Binary protocols

Load references/performance.md when:

  • Large file handling
  • Memory optimization
  • Concurrent operations

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

100+ animated React components (Aceternity UI) for Next.js with Tailwind. Use for hero sections, parallax, 3D effects, or encountering animation, shadcn CLI integration errors.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

secondsky/claude-skills2322026년 10월 20일 업데이트

Secure API authentication with JWT, OAuth 2.0, API keys. Use for authentication systems, third-party integrations, service-to-service communication, or encountering token management, security headers, auth flow errors.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

secondsky/claude-skills2322026년 10월 20일 업데이트

Creates comprehensive API changelogs documenting breaking changes, deprecations, and migration strategies for API consumers. Use when managing API versions, communicating breaking changes, or creating upgrade guides.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

secondsky/claude-skills2322026년 10월 20일 업데이트

Verifies API contracts between services using consumer-driven contracts, schema validation, and tools like Pact. Use when testing microservices communication, preventing breaking changes, or validating OpenAPI specifications.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

secondsky/claude-skills2322026년 10월 20일 업데이트

Master REST and GraphQL API design principles to build intuitive, scalable, and maintainable APIs that delight developers. Use when designing new APIs, reviewing API specifications, or establishing API design standards.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

secondsky/claude-skills2322026년 10월 20일 업데이트

Implements standardized API error responses with proper status codes, logging, and user-friendly messages. Use when building production APIs, implementing error recovery patterns, or integrating error monitoring services.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

secondsky/claude-skills2322026년 10월 20일 업데이트

secondsky의 스킬 모두 보기

이 스킬의 문제 신고