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:
- A Google Cloud account or a Service Account with the necessary permissions to interact with a Bucket.
- Installed the Google Cloud CLI.
- Basic knowledge of NodeJS. You can refer to this guide to set up a NodeJS TypeScript project as used in this article.
Creating a Service Account
Setting roles for necessary permissions
Ensure you have assigned the roles needed to interact with Google Bucket.
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:
Next is the code to create a Bucket and upload a file to the Bucket.
- 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
Post a Comment