Uploading Files to Google Cloud Storage with NodeJS

Introduction

This guide will show you how to upload files to Google Cloud Storage using NodeJS. This method, which separates file storage from logic processing, is commonly used today. Cloud Storage offers an efficient solution for securely storing data, with major providers like Google, Amazon, and Azure leading the way.

Prerequisites

Before you proceed, make sure you have:


Creating a Service Account

Refer to this guide to create a JSON file for your Service Account before moving on to the next steps.


Setting roles for necessary permissions

Ensure you have assigned the roles needed to interact with Google Bucket.

gcloud projects add-iam-policy-binding {project id} \
--member=serviceAccount:{service account username}@{project id}.iam.gserviceaccount.com \
--role=roles/{role}

Execute the following roles one by one: `roles/storage.objectAdmin`, `roles/storage.admin`


Working with NodeJS

After successfully setting up your NodeJS TypeScript project, install the following package to interact with Google Cloud Storage:

yarn add @google-cloud/storage


Next is the code to create a Bucket and upload a file to the Bucket.

import {Bucket, Storage} from '@google-cloud/storage'

const getBucket = async (bucketName: string): Promise<Bucket> => {
try {
const bucket = storage.bucket(bucketName)
await bucket.getMetadata()
return bucket
} catch {
await storage.createBucket(bucketName, {location: 'asia-southeast1'}) // replace your location
return storage.bucket(bucketName)
}
}

const storage = new Storage({
keyFilename: 'local-path/service-account.json',
})
const bucketName = '{project id}-{bucket name}'
const fileName = 'text.txt' // replace your file
const filePath = 'local-path/' + fileName;
const storagePath = `storage_folder_name/${fileName}`

const bucket = await getBucket(bucketName)
const [buckets] = await storage.getBuckets()
const bucketNames = buckets.map(item => item.name)
console.log('Bucket names:', bucketNames)

const result = await bucket.upload(filePath, {
destination: storagePath,
predefinedAcl: 'publicRead',
metadata: {
contentType: 'application/plain',
},
})
console.log('Link download:', result?.[0]?.metadata?.mediaLink)

  • I've checked whether the bucket exists with the above code block. If it doesn't exist, the code will create it. If it does exist, it will upload the file to that bucket and list all bucket names.
  • Make sure you successfully create the `service-account.json` file and have the necessary permissions to interact with the bucket.
  • The bucket name must follow the format `{project id}-{bucket name}` and must be unique (it can't duplicate an existing bucket name).
  • After executing the program, it will show the download link for the successfully uploaded file, which will look like this: `https://storage.googleapis.com/{bucket name}/{folders}/{file name}`


You can then access that URL to download the file or check the Google Cloud Bucket to verify the successful upload.


Feel free to share your thoughts in the comments section, and remember to like, share, and follow for more insightful content in the future!

Comments

Popular posts from this blog

Kubernetes Practice Series

NodeJS Practice Series

Docker Practice Series

React Practice Series

Sitemap

Deploying a NodeJS Server on Google Kubernetes Engine

Setting up Kubernetes Dashboard with Kind

A Handy Guide to Using Dynamic Import in JavaScript

DevOps Practice Series

Create API Gateway with fast-gateway