read write file to google cloud storage
Others Web Development

How to Read/Write file to Google Cloud Storage with Javascript

In this post, we’ll show you how to read/write JSON file from Google Cloud Storage bucket with JavaScript (Node.js)

Setting up Credential

You’ll need to install google-cloud/storage first using npm install.

Note: if you’re using Google Cloud Function, just add google-cloud/storage to package.json and skip this step

npm install --save @google-cloud/storage

You’ll also need to provide Google¬† cloud service account credential by exporting the GOOGLE_APPLICATION_CREDENTIALS environment variable from service account JSON file. (see how to download credential JSON file here)

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/service-account-file.json"

Reading File from Cloud Storage

First you’ll need to import google-cloud/storage

const {Storage} = require('@google-cloud/storage');
const storage = new Storage();

Then you can read the file from bucket as follow. For this example, we’re reading JSON file which could be done via parsing the content returned from download()

async function readFilefromCloudStorage() {
  const contents = await storage.bucket(BUCKET_NAME).file(FILE_NAME).download();
  const jsonContent = JSON.parse(contents);
}

Writing File to Cloud Storage

Writing the file is very similar to reading. In this case, we’re writing JSON file so we’ll need to stringify it first. Also catch and handle any error as needed.

Note that writing/uploading file with this method will overwrite the file (or create another version per bucket’s setting)

async function writeFileToCloudStorage() { 
   try {
     await storage.bucket(BUCKET_NAME).file(FILE_NAME).save(JSON.stringify(contents));
   } catch(e) {
      console.log(e);
  }
}
Written By

 

Leave a Reply

Your email address will not be published.

error: