1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Bun でファイル入出力と S3 操作をシンプル実装

Last updated at Posted at 2025-03-28

要約

File I/O

const file = Bun.file("foo.txt");

// Write
await Bun.write(file, "foo!");

// Read
const data = await file.text();

// Delete
await file.delete();

S3 API

const metadata = s3.file("123.json");

// Upload
await write(metadata, JSON.stringify({ name: "John", age: 30 }));

// Download
const data = await metadata.json();

// Delete
await metadata.delete();

ね?簡単でしょ?

詳しくは Bun 公式ドキュメントを参照してください

ここが良い!便利ポイント

使用方法を羅列しても、ただの公式ドキュメント翻訳になってしまいますので、
ここでは Bun File I/O のおすすめポイントを紹介していきます。

シンプルに書ける

ファイルに何か書き込みたい!読み出したい!

const file = Bun.file("foo.txt"); // Create BunFile instance

await Bun.write(file, "foo!");    // Write
const data = await file.text();   // Read

はい!これだけ!
BunFile という instance を軸に、様々な操作を直感的に書くことができます。

さらにこの記述方法が File I/O と S3 API で共通のため、
Object Storage のファイルでも、ローカルのファイルかのように扱うことが可能です。

また、環境変数から自動で S3 への接続情報を取得するため、S3 クライアントを定義する必要はありません。

もちろん、従来のようにクライアントを明示することも可能です。

import { S3Client } from "bun";

const client = new S3Client({
  accessKeyId: "your-access-key",
  secretAccessKey: "your-secret-key",
  bucket: "my-bucket",
});

様々なフォーマットに対応

もちろん text だけでなく、任意の形式での読み書きが可能です。

const foo = Bun.file("foo.txt");

await foo.text(); // contents as a string
await foo.stream(); // contents as ReadableStream
await foo.arrayBuffer(); // contents as ArrayBuffer
await foo.bytes(); // contents as Uint8Array

出典:https://bun.sh/docs/api/file-io#reading-files-bun-file

依存関係を増やさない

従来では S3 互換 Object Storage の操作には、AWS SDK などを利用するのが通例でした。
ただ、毎回インポートして S3 クライアントを作成して、コマンドを送信して…とやるのは手間ですよね。

Bun runtime を使ってさえいれば、別途依存ライブラリを追加することなく、簡単に S3 への入出力を実装することができます。

所感

Node.js 互換の JavaScript runtime として開発が進められている Bun ですが、Bun runtime 固有の便利な機能、記法も増えてきました。

しかし、大手サーバレスサービスなどにデプロイをしたいとなると、結局 Node.js 前提で使えない…というケースが頻発するため、ぜひ Bun にはシェアを伸ばしていってもらい、対応サービスの拡大を頑張ってもらいたいですね。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?