How to upload a file to GCP bucket in NodeJs
We have recently posted a guide on how we can download files from a GCP bucket and provide it from a REST API. In this article, we will show how we can upload
a file to the bucket.
Prerequisites
- Authentication to GCP (
gcloud auth login
from terminal) or use service account and set env variable like:export GOOGLE_APPLICATION_CREDENTIALS="/path/to/my-service-account-key.json"
. - Bucket enabled in GCP
- Type
npm install @google-cloud/storage
in your terminal
Let's write our bucketHandler.js class
const { Storage } = require("@google-cloud/storage"); const fs = require("fs"); const storage = new Storage(); const bucketName = "algobook"; class BucketHandler { async uploadFile(file, fileName, bucketFolder) { return new Promise((resolve, reject) => { const stream = storage .bucket(bucketName) .file(`${bucketFolder}/${fileName}`) .createWriteStream(); stream.on("error", (err) => { reject(err); }); stream.on("finish", () => { resolve("Done"); }); stream.end(file); }); } } (async () => { const file = fs.readFileSync("cat.png"); const bucketHandler = new BucketHandler(); await bucketHandler.uploadFile(file, "myCat.png", "example-folder"); })(); module.exports = BucketHandler;
Run the code using this command:
node bucketHandler.js
In this example, we are reading in a local file in the project cat.png
and uploading it to the algobook
bucket in the example-folder
and giving it a new name myCat.png
. By running the code, we will now have a file in our bucket called myCat.png
.
Navigating to our GCP bucket, we can now see that our file is successfully uploaded.
Summary
All right. So this was a super short guide on how to upload files to our GCP bucket. We used a local file located in our project. If you want to tie this together with perhaps a client application where you upload a file and sending it to an API, we have excellent guides for that as well. I will link to them below.