I server di produzione spesso leggono, caricano e scrivono file su servizi di archiviazione oggetti compatibili con S3 invece che sul filesystem locale. Storicamente, questo significa che le API del filesystem locale usate in sviluppo non possono essere usate in produzione. Quando usi Bun, le cose sono diverse.
L'API S3 di Bun è veloce
Bun fornisce binding nativi veloci per interagire con servizi di archiviazione oggetti compatibili con S3. L'API S3 di Bun è progettata per essere semplice e simile alle API Response e Blob di fetch (come le API del filesystem locale di Bun).
import { s3, write, S3Client } from "bun";
// Bun.s3 legge le variabili d'ambiente per le credenziali
// file() restituisce un riferimento lazy a un file su S3
const metadata = s3.file("123.json");
// Scarica da S3 come JSON
const data = await metadata.json();
// Carica su S3
await write(metadata, JSON.stringify({ name: "John", age: 30 }));
// Presigna un URL (sincrono - nessuna richiesta di rete necessaria)
const url = metadata.presign({
acl: "public-read",
expiresIn: 60 * 60 * 24, // 1 giorno
});
// Elimina il file
await metadata.delete();S3 è lo standard de facto per il filesystem internet. L'API S3 di Bun funziona con servizi di archiviazione compatibili con S3 come:
- AWS S3
- Cloudflare R2
- DigitalOcean Spaces
- MinIO
- Backblaze B2
- ...e qualsiasi altro servizio di archiviazione compatibile con S3
Utilizzo di Base
Ci sono diversi modi per interagire con l'API S3 di Bun.
Bun.S3Client e Bun.s3
Bun.s3 è equivalente a new Bun.S3Client(), basandosi sulle variabili d'ambiente per le credenziali.
Per impostare esplicitamente le credenziali, passale al costruttore Bun.S3Client.
import { S3Client } from "bun";
const client = new S3Client({
accessKeyId: "tua-access-key",
secretAccessKey: "tua-secret-key",
bucket: "tuo-bucket",
// sessionToken: "..."
// acl: "public-read",
// endpoint: "https://s3.us-east-1.amazonaws.com",
// endpoint: "https://<account-id>.r2.cloudflarestorage.com", // Cloudflare R2
// endpoint: "https://<region>.digitaloceanspaces.com", // DigitalOcean Spaces
// endpoint: "http://localhost:9000", // MinIO
});
// Bun.s3 è un singleton globale equivalente a `new Bun.S3Client()`Lavorare con File S3
Il metodo file in S3Client restituisce un riferimento lazy a un file su S3.
// Un riferimento lazy a un file su S3
const s3file: S3File = client.file("123.json");Come Bun.file(path), il metodo file di S3Client è sincrono. Non esegue zero richieste di rete finché non chiami un metodo che dipende da una richiesta di rete.
Leggere file da S3
Se hai usato l'API fetch, hai familiarità con le API Response e Blob. S3File estende Blob. Gli stessi metodi che funzionano su Blob funzionano anche su S3File.
// Leggi un S3File come testo
const text = await s3file.text();
// Leggi un S3File come JSON
const json = await s3file.json();
// Leggi un S3File come ArrayBuffer
const buffer = await s3file.arrayBuffer();
// Ottieni solo i primi 1024 byte
const partial = await s3file.slice(0, 1024).text();
// Stream del file
const stream = s3file.stream();
for await (const chunk of stream) {
console.log(chunk);
}Ottimizzazione della memoria
Metodi come text(), json(), bytes(), o arrayBuffer() evitano di duplicare la stringa o i byte in memoria quando possibile.
Se il testo è ASCII, Bun trasferisce direttamente la stringa a JavaScriptCore (il motore) senza transcodifica e senza duplicare la stringa in memoria. Quando usi .bytes() o .arrayBuffer(), eviterà anche di duplicare i byte in memoria.
Questi metodi helper non solo semplificano l'API, ma la rendono anche più veloce.
Scrivere e caricare file su S3
Scrivere su S3 è altrettanto semplice.
// Scrivi una stringa (sostituendo il file)
await s3file.write("Ciao Mondo!");
// Scrivi un Buffer (sostituendo il file)
await s3file.write(Buffer.from("Ciao Mondo!"));
// Scrivi una Response (sostituendo il file)
await s3file.write(new Response("Ciao Mondo!"));
// Scrivi con tipo di contenuto
await s3file.write(JSON.stringify({ name: "John", age: 30 }), {
type: "application/json",
});
// Scrivi usando un writer (streaming)
const writer = s3file.writer({ type: "application/json" });
writer.write("Ciao");
writer.write(" Mondo!");
await writer.end();
// Scrivi usando Bun.write
await Bun.write(s3file, "Ciao Mondo!");Lavorare con file di grandi dimensioni (stream)
Bun gestisce automaticamente i caricamenti multipart per file di grandi dimensioni e fornisce capacità di streaming. La stessa API che funziona per i file locali funziona anche per i file S3.
// Scrivi un file di grandi dimensioni
const bigFile = Buffer.alloc(10 * 1024 * 1024); // 10MB
const writer = s3file.writer({
// Riprova automaticamente in caso di errori di rete fino a 3 volte
retry: 3,
// Metti in coda fino a 10 richieste alla volta
queueSize: 10,
// Carica in chunk da 5 MB
partSize: 5 * 1024 * 1024,
});
for (let i = 0; i < 10; i++) {
writer.write(bigFile);
await writer.flush();
}
await writer.end();URL con Firma (Presigning)
Quando il tuo servizio di produzione deve permettere agli utenti di caricare file sul tuo server, è spesso più affidabile per l'utente caricare direttamente su S3 invece che il tuo server faccia da intermediario.
Per facilitare questo, puoi presignare URL per file S3. Questo genera un URL con una firma che permette a un utente di caricare in modo sicuro quel file specifico su S3, senza esporre le tue credenziali o concedere accesso non necessario al tuo bucket.
Il comportamento predefinito è generare un URL GET che scade in 24 ore. Bun tenta di dedurre il tipo di contenuto dall'estensione del file. Se la deduzione non è possibile, userà application/octet-stream come default.
import { s3 } from "bun";
// Genera un URL con firma che scade in 24 ore (default)
const download = s3.presign("mio-file.txt"); // GET, text/plain, scade in 24 ore
const upload = s3.presign("mio-file", {
expiresIn: 3600, // 1 ora
method: "PUT",
type: "application/json", // Nessuna estensione per dedurre, quindi possiamo specificare che il tipo di contenuto sia JSON
});
// Puoi chiamare .presign() se hai un riferimento al file, ma evita di farlo
// a meno che tu non abbia già un riferimento (per evitare uso di memoria).
const myFile = s3.file("mio-file.txt");
const presignedFile = myFile.presign({
expiresIn: 3600, // 1 ora
});Impostare ACL
Per impostare una ACL (lista di controllo accessi) su un URL con firma, passa l'opzione acl:
const url = s3file.presign({
acl: "public-read",
expiresIn: 3600,
});Puoi passare una delle seguenti ACL:
| ACL | Spiegazione |
|---|---|
"public-read" | L'oggetto è leggibile dal pubblico. |
"private" | L'oggetto è leggibile solo dal proprietario del bucket. |
"public-read-write" | L'oggetto è leggibile e scrivibile dal pubblico. |
"authenticated-read" | L'oggetto è leggibile dal proprietario del bucket e utenti autenticati. |
"aws-exec-read" | L'oggetto è leggibile dall'account AWS che ha fatto la richiesta. |
"bucket-owner-read" | L'oggetto è leggibile dal proprietario del bucket. |
"bucket-owner-full-control" | L'oggetto è leggibile e scrivibile dal proprietario del bucket. |
"log-delivery-write" | L'oggetto è scrivibile dai servizi AWS usati per la consegna log. |
URL con Scadenza
Per impostare un tempo di scadenza per un URL con firma, passa l'opzione expiresIn.
const url = s3file.presign({
// Secondi
expiresIn: 3600, // 1 ora
// lista di controllo accessi
acl: "public-read",
// metodo HTTP
method: "PUT",
});method
Per impostare il metodo HTTP per un URL con firma, passa l'opzione method.
const url = s3file.presign({
method: "PUT",
// method: "DELETE",
// method: "GET",
// method: "HEAD",
// method: "POST",
// method: "PUT",
});new Response(S3File)
Per reindirizzare rapidamente gli utenti a un URL con firma per un file S3, passa un'istanza S3File a un oggetto Response come body.
Questo reindirizzerà automaticamente l'utente all'URL con firma per il file S3, risparmiandoti il costo di memoria, tempo e banda del download del file sul tuo server e dell'invio all'utente.
const response = new Response(s3file);
console.log(response);Response (0 KB) {
ok: false,
url: "",
status: 302,
statusText: "",
headers: Headers {
"location": "https://<account-id>.r2.cloudflarestorage.com/...",
},
redirected: true,
bodyUsed: false
}Supporto per Servizi Compatibili con S3
L'implementazione S3 di Bun funziona con qualsiasi servizio di archiviazione compatibile con S3. Basta specificare l'endpoint appropriato:
Usare Bun's S3Client con AWS S3
AWS S3 è il default. Puoi anche passare un'opzione region invece di un'opzione endpoint per AWS S3.
import { S3Client } from "bun";
// AWS S3
const s3 = new S3Client({
accessKeyId: "access-key",
secretAccessKey: "secret-key",
bucket: "my-bucket",
// endpoint: "https://s3.us-east-1.amazonaws.com",
// region: "us-east-1",
});Usare Bun's S3Client con Google Cloud Storage
Per usare il client S3 di Bun con Google Cloud Storage, imposta endpoint su "https://storage.googleapis.com" nel costruttore S3Client.
import { S3Client } from "bun";
// Google Cloud Storage
const gcs = new S3Client({
accessKeyId: "access-key",
secretAccessKey: "secret-key",
bucket: "my-bucket",
endpoint: "https://storage.googleapis.com",
});Usare Bun's S3Client con Cloudflare R2
Per usare il client S3 di Bun con Cloudflare R2, imposta endpoint sull'endpoint R2 nel costruttore S3Client. L'endpoint R2 include il tuo ID account.
import { S3Client } from "bun";
// CloudFlare R2
const r2 = new S3Client({
accessKeyId: "access-key",
secretAccessKey: "secret-key",
bucket: "my-bucket",
endpoint: "https://<account-id>.r2.cloudflarestorage.com",
});Usare Bun's S3Client con DigitalOcean Spaces
Per usare il client S3 di Bun con DigitalOcean Spaces, imposta endpoint sull'endpoint DigitalOcean Spaces nel costruttore S3Client.
import { S3Client } from "bun";
const spaces = new S3Client({
accessKeyId: "access-key",
secretAccessKey: "secret-key",
bucket: "my-bucket",
// region: "nyc3",
endpoint: "https://<region>.digitaloceanspaces.com",
});Usare Bun's S3Client con MinIO
Per usare il client S3 di Bun con MinIO, imposta endpoint sull'URL su cui MinIO è in esecuzione nel costruttore S3Client.
import { S3Client } from "bun";
const minio = new S3Client({
accessKeyId: "access-key",
secretAccessKey: "secret-key",
bucket: "my-bucket",
// Assicurati di usare l'URL endpoint corretto
// Potrebbe non essere localhost in produzione!
endpoint: "http://localhost:9000",
});Usare Bun's S3Client con supabase
Per usare il client S3 di Bun con supabase, imposta endpoint sull'endpoint supabase nel costruttore S3Client. L'endpoint supabase include il tuo ID account e il percorso /storage/v1/s3. Assicurati di impostare "Abilita connessione tramite protocollo S3" nella dashboard supabase in https://supabase.com/dashboard/project/<account-id>/settings/storage e di impostare la regione informata nella stessa sezione.
import { S3Client } from "bun";
const supabase = new S3Client({
accessKeyId: "access-key",
secretAccessKey: "secret-key",
bucket: "my-bucket",
region: "us-west-1",
endpoint: "https://<account-id>.supabase.co/storage/v1/s3/storage",
});Usare Bun's S3Client con endpoint S3 Virtual Hosted-Style
Quando usi un endpoint S3 Virtual Hosted-Style, devi impostare l'opzione virtualHostedStyle a true.
NOTE
- Se non specifichi un endpoint, Bun determinerà automaticamente l'endpoint AWS S3 usando la regione e il bucket forniti. - Se nessuna regione è specificata, Bun usa us-east-1 come default. - Se fornisci esplicitamente un endpoint, non devi specificare un nome bucket.import { S3Client } from "bun";
// Endpoint AWS S3 dedotto da regione e bucket
const s3 = new S3Client({
accessKeyId: "access-key",
secretAccessKey: "secret-key",
bucket: "my-bucket",
virtualHostedStyle: true,
// endpoint: "https://my-bucket.s3.us-east-1.amazonaws.com",
// region: "us-east-1",
});
// AWS S3
const s3WithEndpoint = new S3Client({
accessKeyId: "access-key",
secretAccessKey: "secret-key",
endpoint: "https://<bucket-name>.s3.<region>.amazonaws.com",
virtualHostedStyle: true,
});
// Cloudflare R2
const r2WithEndpoint = new S3Client({
accessKeyId: "access-key",
secretAccessKey: "secret-key",
endpoint: "https://<bucket-name>.<account-id>.r2.cloudflarestorage.com",
virtualHostedStyle: true,
});Credenziali
Le credenziali sono una delle parti più difficili dell'uso di S3, e abbiamo cercato di renderlo il più semplice possibile. Di default, Bun legge le seguenti variabili d'ambiente per le credenziali.
| Nome opzione | Variabile d'ambiente |
|---|---|
accessKeyId | S3_ACCESS_KEY_ID |
secretAccessKey | S3_SECRET_ACCESS_KEY |
region | S3_REGION |
endpoint | S3_ENDPOINT |
bucket | S3_BUCKET |
sessionToken | S3_SESSION_TOKEN |
Se la variabile d'ambiente S3_* non è impostata, Bun controllerà anche la variabile d'ambiente AWS_* per ciascuna delle opzioni sopra.
| Nome opzione | Variabile d'ambiente fallback |
|---|---|
accessKeyId | AWS_ACCESS_KEY_ID |
secretAccessKey | AWS_SECRET_ACCESS_KEY |
region | AWS_REGION |
endpoint | AWS_ENDPOINT |
bucket | AWS_BUCKET |
sessionToken | AWS_SESSION_TOKEN |
Queste variabili d'ambiente sono lette dai file .env o dall'ambiente del processo al momento dell'inizializzazione (process.env non è usato per questo).
Questi default sono sovrascritti dalle opzioni che passi a s3.file(credentials), new Bun.S3Client(credentials), o qualsiasi dei metodi che accettano credenziali. Quindi se, per esempio, usi le stesse credenziali per bucket diversi, puoi impostare le credenziali una volta nel tuo file .env e poi passare bucket: "my-bucket" alla funzione s3.file() senza dover specificare di nuovo tutte le credenziali.
Oggetti S3Client
Quando non usi variabili d'ambiente o usi bucket multipli, puoi creare un oggetto S3Client per impostare esplicitamente le credenziali.
import { S3Client } from "bun";
const client = new S3Client({
accessKeyId: "tua-access-key",
secretAccessKey: "tua-secret-key",
bucket: "tuo-bucket",
// sessionToken: "..."
endpoint: "https://s3.us-east-1.amazonaws.com",
// endpoint: "https://<account-id>.r2.cloudflarestorage.com", // Cloudflare R2
// endpoint: "http://localhost:9000", // MinIO
});
// Scrivi usando una Response
await file.write(new Response("Ciao Mondo!"));
// Presigna un URL
const url = file.presign({
expiresIn: 60 * 60 * 24, // 1 giorno
acl: "public-read",
});
// Elimina il file
await file.delete();S3Client.prototype.write
Per caricare o scrivere un file su S3, chiama write sull'istanza S3Client.
const client = new Bun.S3Client({
accessKeyId: "tua-access-key",
secretAccessKey: "tua-secret-key",
endpoint: "https://s3.us-east-1.amazonaws.com",
bucket: "tuo-bucket",
});
await client.write("mio-file.txt", "Ciao Mondo!");
await client.write("mio-file.txt", new Response("Ciao Mondo!"));
// equivalente a
// await client.file("mio-file.txt").write("Ciao Mondo!");S3Client.prototype.delete
Per eliminare un file da S3, chiama delete sull'istanza S3Client.
const client = new Bun.S3Client({
accessKeyId: "tua-access-key",
secretAccessKey: "tua-secret-key",
bucket: "tuo-bucket",
});
await client.delete("mio-file.txt");
// equivalente a
// await client.file("mio-file.txt").delete();S3Client.prototype.exists
Per controllare se un file esiste in S3, chiama exists sull'istanza S3Client.
const client = new Bun.S3Client({
accessKeyId: "tua-access-key",
secretAccessKey: "tua-secret-key",
bucket: "tuo-bucket",
});
const exists = await client.exists("mio-file.txt");
// equivalente a
// const exists = await client.file("mio-file.txt").exists();S3File
Le istanze S3File sono create chiamando il metodo dell'istanza S3Client o la funzione s3.file(). Come Bun.file(), le istanze S3File sono lazy. Non si riferiscono a qualcosa che necessariamente esiste al momento della creazione. Ecco perché tutti i metodi che non coinvolgono richieste di rete sono completamente sincroni.
interface S3File extends Blob {
slice(start: number, end?: number): S3File;
exists(): Promise<boolean>;
unlink(): Promise<void>;
presign(options: S3Options): string;
text(): Promise<string>;
json(): Promise<any>;
bytes(): Promise<Uint8Array>;
arrayBuffer(): Promise<ArrayBuffer>;
stream(options: S3Options): ReadableStream;
write(
data: string | Uint8Array | ArrayBuffer | Blob | ReadableStream | Response | Request,
options?: BlobPropertyBag,
): Promise<number>;
exists(options?: S3Options): Promise<boolean>;
unlink(options?: S3Options): Promise<void>;
delete(options?: S3Options): Promise<void>;
presign(options?: S3Options): string;
stat(options?: S3Options): Promise<S3Stat>;
/**
* Size non è disponibile sincronamente perché richiede una richiesta di rete.
*
* @deprecated Usa `stat()` invece.
*/
size: NaN;
// ... altro omesso per brevità
}Come Bun.file(), S3File estende Blob, quindi tutti i metodi disponibili su Blob sono disponibili anche su S3File. La stessa API per leggere dati da un file locale è disponibile anche per leggere dati da S3.
| Metodo | Output |
|---|---|
await s3File.text() | string |
await s3File.bytes() | Uint8Array |
await s3File.json() | JSON |
await s3File.stream() | ReadableStream |
await s3File.arrayBuffer() | ArrayBuffer |
Questo significa che usare istanze S3File con fetch(), Response, e altre API web che accettano istanze Blob funziona semplicemente.
Letture parziali con slice
Per leggere un intervallo parziale di un file, puoi usare il metodo slice.
const partial = s3file.slice(0, 1024);
// Leggi l'intervallo parziale come Uint8Array
const bytes = await partial.bytes();
// Leggi l'intervallo parziale come stringa
const text = await partial.text();Internamente, questo funziona usando l'header HTTP Range per richiedere solo i byte che vuoi. Questo metodo slice è lo stesso di Blob.prototype.slice.
Eliminare file da S3
Per eliminare un file da S3, puoi usare il metodo delete.
await s3file.delete();
// await s3File.unlink();delete è lo stesso di unlink.
Codici di errore
Quando l'API S3 di Bun lancia un errore, avrà una proprietà code che corrisponde a uno dei seguenti valori:
ERR_S3_MISSING_CREDENTIALSERR_S3_INVALID_METHODERR_S3_INVALID_PATHERR_S3_INVALID_ENDPOINTERR_S3_INVALID_SIGNATUREERR_S3_INVALID_SESSION_TOKEN
Quando il servizio di archiviazione oggetti S3 restituisce un errore (cioè, non Bun), sarà un'istanza S3Error (un'istanza Error con il nome "S3Error").
Metodi statici S3Client
La classe S3Client fornisce diversi metodi statici per interagire con S3.
S3Client.write (statico)
Per scrivere dati direttamente su un percorso nel bucket, puoi usare il metodo statico S3Client.write.
import { S3Client } from "bun";
const credentials = {
accessKeyId: "tua-access-key",
secretAccessKey: "tua-secret-key",
bucket: "tuo-bucket",
// endpoint: "https://s3.us-east-1.amazonaws.com",
// endpoint: "https://<account-id>.r2.cloudflarestorage.com", // Cloudflare R2
};
// Scrivi stringa
await S3Client.write("mio-file.txt", "Ciao Mondo");
// Scrivi JSON con tipo
await S3Client.write("data.json", JSON.stringify({ hello: "mondo" }), {
...credentials,
type: "application/json",
});
// Scrivi da fetch
const res = await fetch("https://example.com/data");
await S3Client.write("data.bin", res, credentials);
// Scrivi con ACL
await S3Client.write("public.html", html, {
...credentials,
acl: "public-read",
type: "text/html",
});Questo è equivalente a chiamare new S3Client(credentials).write("mio-file.txt", "Ciao Mondo").
S3Client.presign (statico)
Per generare un URL con firma per un file S3, puoi usare il metodo statico S3Client.presign.
import { S3Client } from "bun";
const credentials = {
accessKeyId: "tua-access-key",
secretAccessKey: "tua-secret-key",
bucket: "tuo-bucket",
// endpoint: "https://s3.us-east-1.amazonaws.com",
// endpoint: "https://<account-id>.r2.cloudflarestorage.com", // Cloudflare R2
};
const url = S3Client.presign("mio-file.txt", {
...credentials,
expiresIn: 3600,
});Questo è equivalente a chiamare new S3Client(credentials).presign("mio-file.txt", { expiresIn: 3600 }).
S3Client.list (statico)
Per elencare alcuni o tutti (fino a 1.000) oggetti in un bucket, puoi usare il metodo statico S3Client.list.
import { S3Client } from "bun";
const credentials = {
accessKeyId: "tua-access-key",
secretAccessKey: "tua-secret-key",
bucket: "tuo-bucket",
// endpoint: "https://s3.us-east-1.amazonaws.com",
// endpoint: "https://<account-id>.r2.cloudflarestorage.com", // Cloudflare R2
};
// Elenca (fino a) 1000 oggetti nel bucket
const allObjects = await S3Client.list(null, credentials);
// Elenca (fino a) 500 oggetti sotto il prefisso `uploads/`, con campo owner per ogni oggetto
const uploads = await S3Client.list({
prefix: 'uploads/',
maxKeys: 500,
fetchOwner: true,
}, credentials);
// Controlla se ci sono più risultati disponibili
if (uploads.isTruncated) {
// Elenca il prossimo batch di oggetti sotto il prefisso `uploads/`
const moreUploads = await S3Client.list({
prefix: 'uploads/',
maxKeys: 500,
startAfter: uploads.contents!.at(-1).key
fetchOwner: true,
}, credentials);
}Questo è equivalente a chiamare new S3Client(credentials).list().
S3Client.exists (statico)
Per controllare se un file S3 esiste, puoi usare il metodo statico S3Client.exists.
import { S3Client } from "bun";
const credentials = {
accessKeyId: "tua-access-key",
secretAccessKey: "tua-secret-key",
bucket: "tuo-bucket",
// endpoint: "https://s3.us-east-1.amazonaws.com",
// endpoint: "https://<account-id>.r2.cloudflarestorage.com", // Cloudflare R2
};
const exists = await S3Client.exists("mio-file.txt", credentials);Lo stesso metodo funziona anche su istanze S3File.
import { s3 } from "bun";
const s3file = s3.file("mio-file.txt", {
// ...credenziali,
});
const exists = await s3file.exists();S3Client.size (statico)
Per controllare rapidamente la dimensione di un file S3 senza scaricarlo, puoi usare il metodo statico S3Client.size.
import { S3Client } from "bun";
const credentials = {
accessKeyId: "tua-access-key",
secretAccessKey: "tua-secret-key",
bucket: "tuo-bucket",
// endpoint: "https://s3.us-east-1.amazonaws.com",
// endpoint: "https://<account-id>.r2.cloudflarestorage.com", // Cloudflare R2
};
const bytes = await S3Client.size("mio-file.txt", credentials);Questo è equivalente a chiamare new S3Client(credentials).size("mio-file.txt").
S3Client.stat (statico)
Per ottenere la dimensione, etag e altri metadati di un file S3, puoi usare il metodo statico S3Client.stat.
import { S3Client } from "bun";
const credentials = {
accessKeyId: "tua-access-key",
secretAccessKey: "tua-secret-key",
bucket: "tuo-bucket",
// endpoint: "https://s3.us-east-1.amazonaws.com",
// endpoint: "https://<account-id>.r2.cloudflarestorage.com", // Cloudflare R2
};
const stat = await S3Client.stat("mio-file.txt", credentials);{
etag: "\"7a30b741503c0b461cc14157e2df4ad8\"",
lastModified: 2025-01-07T00:19:10.000Z,
size: 1024,
type: "text/plain;charset=utf-8",
}S3Client.delete (statico)
Per eliminare un file S3, puoi usare il metodo statico S3Client.delete.
import { S3Client } from "bun";
const credentials = {
accessKeyId: "tua-access-key",
secretAccessKey: "tua-secret-key",
bucket: "tuo-bucket",
// endpoint: "https://s3.us-east-1.amazonaws.com",
};
await S3Client.delete("mio-file.txt", credentials);
// equivalente a
// await new S3Client(credentials).delete("mio-file.txt");
// S3Client.unlink è alias di S3Client.delete
await S3Client.unlink("mio-file.txt", credentials);Protocollo s3://
Per rendere più facile usare lo stesso codice per file locali e file S3, il protocollo s3:// è supportato in fetch e Bun.file().
const response = await fetch("s3://mio-bucket/mio-file.txt");
const file = Bun.file("s3://mio-bucket/mio-file.txt");Puoi anche passare opzioni s3 alle funzioni fetch e Bun.file.
const response = await fetch("s3://mio-bucket/mio-file.txt", {
s3: {
accessKeyId: "tua-access-key",
secretAccessKey: "tua-secret-key",
endpoint: "https://s3.us-east-1.amazonaws.com",
},
headers: {
range: "bytes=0-1023",
},
});UTF-8, UTF-16 e BOM (byte order mark)
Come Response e Blob, S3File assume la codifica UTF-8 di default.
Quando chiami uno dei metodi text() o json() su un S3File:
- Quando viene rilevato un byte order mark (BOM) UTF-16, sarà trattato come UTF-16. JavaScriptCore supporta nativamente UTF-16, quindi salta il processo di transcodifica UTF-8 (e rimuove il BOM). Questo è per lo più buono, ma significa che se hai caratteri surrogate pair non validi nella tua stringa UTF-16, saranno passati a JavaScriptCore (come nel codice sorgente).
- Quando viene rilevato un BOM UTF-8, viene rimosso prima che la stringa sia passata a JavaScriptCore e i codepoint UTF-8 non validi sono sostituiti con il carattere di sostituzione Unicode (
\uFFFD). - UTF-32 non è supportato.