read text file from node js firebase storage

How to Read Text File from Node.js Firebase Storage

If you're working with Firebase and Node.js, you might need to read a text file stored in Firebase Storage. Here's how to do it:

Method 1: Using Firebase Admin SDK

The Firebase Admin SDK allows you to interact with Firebase services from privileged environments such as servers or cloud functions. It provides a convenient way to access Firebase Storage from Node.js.

First, install the Firebase Admin SDK:

npm install firebase-admin

Then, initialize the SDK:

// Initialize Firebase Admin SDK
const admin = require("firebase-admin");

// Fetch the service account key JSON file contents
const serviceAccount = require("./path/to/serviceAccountKey.json");

// Initialize Firebase Admin SDK
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  storageBucket: ""
});

// Initialize Cloud Storage bucket
const bucket = admin.storage().bucket();

Replace <your-storage-bucket> with the name of your Storage bucket.

Now, you can use the bucket object to read a text file:

// Read a text file
const file = bucket.file("path/to/text-file.txt");

file.download(function(err, contents) {
  if (!err) {
    console.log(contents.toString());
  }
});

The download() method downloads the file from Storage and returns its contents as a buffer. You can convert the buffer to a string using the toString() method.

Method 2: Using Firebase Storage REST API

If you don't want to use the Firebase Admin SDK, you can use the Firebase Storage REST API to read a text file from Node.js.

First, get a Firebase access token:

// Fetch Firebase access token
const { GoogleAuth } = require('google-auth-library');

async function getAccessToken() {
  const auth = new GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/firebase']
  });

  const { access_token } = await auth.getAccessToken();
  return access_token;
}

const accessToken = await getAccessToken();

Next, make an HTTP request to download the file:

// Make HTTP request to download file
const https = require('https');

const options = {
  hostname: '.storage.googleapis.com',
  path: '/path/to/text-file.txt',
  headers: {
    Authorization: `Bearer ${accessToken}`
  }
};

https.get(options, (res) => {
  let data = '';

  res.on('data', (chunk) => {
    data += chunk;
  });

  res.on('end', () => {
    console.log(data);
  });
});

Replace <your-storage-bucket> with the name of your Storage bucket, and /path/to/text-file.txt with the path to your text file.

Conclusion

There are two ways to read a text file from Node.js Firebase Storage: using the Firebase Admin SDK or the Firebase Storage REST API. Both methods are straightforward and easy to use. Choose the one that suits your needs best.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe