0

Upload An Object

by
Published Jul 17, 2024

Upload an object to a Google Cloud Storage bucket, [See the docs](https://googleapis.dev/nodejs/storage/latest/Bucket.html#upload)

Script gcloud Verified

The script

Submitted by hugo697 Bun
Verified 692 days ago
1
import { Storage } from "@google-cloud/storage";
2

3
type Base64 = string;
4

5
type Gcloud = {
6
  type: string;
7
  project_id: string;
8
  private_key_id: string;
9
  private_key: string;
10
  client_email: string;
11
  client_id: string;
12
  auth_uri: string;
13
  token_uri: string;
14
  auth_provider_x509_cert_url: string;
15
  client_x509_cert_url: string;
16
  universe_domain: string;
17
};
18

19
export async function main(
20
  resource: Gcloud,
21
  bucketName: string,
22
  fileName: string,
23
  file: Base64
24
) {
25
  const storageClient = new Storage({
26
    credentials: resource,
27
    projectId: resource.project_id,
28
  });
29

30
  const buffer = Buffer.from(file, "base64");
31

32
  await storageClient.bucket(bucketName).file(fileName).save(buffer);
33

34
  const [metadata] = await storageClient
35
    .bucket(bucketName)
36
    .file(fileName)
37
    .getMetadata();
38

39
  return metadata;
40
}
41