Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get storage file.txt content within cloud function

I have a file.txt in the cloud storage and I want to read its content (create an array with its words) within a cloud function.

var myBucket = gcs.bucket(bucket_name);
var myFile = myBucket.file(file_name);

myFile.download().then(function(err, data) {
   if (data) {
     response.send(data.toString());
   }
});

When I run this cloud function I get the following error:

ApiError: [email protected] does not have storage.objects.get access to the file

I already went to the IAM area and add this role/permission to this service account but I keep getting this error.

Can someone help me?

Thanks in advance.

like image 387
Henrique Schorr Avatar asked Nov 30 '25 16:11

Henrique Schorr


1 Answers

Assuming you want to save the content of a CSV file to Firestore/Realtime database.

const functions = require('firebase-functions');
const gcs = require('@google-cloud/storage')();
const path = require('path');

exports.uploadHandler = functions.storage.object().onFinalize((object) => {
    const filename = path.basename(object.name);
    const bucket = gcs.bucket(object.bucket);

    if (object.contentType !== 'text/csv') {
        console.log('This is not a CSV file.');
        return null;
    }

    bucket.file(filename).download((err, contents) => {
        if (err) {
            console.log('error', err);
            return null
        }

        toJSON(contents.toString());
    });
});

function toJSON(content) {
    const rows = content.split("\n");
    const header = rows[0].split(',');

    for (let i = 1; i < rows.length; i++) {
        const cells = rows[i].split(',');
        const jsn = {};
        for (let j = 0; j < cells.length; j++) {
            if (cells[j] !== '') jsn[header[j]] = cells[j];
        }

        jsn[header[0]] && toDB(jsn)
    }
}

function toDB(jsn) {
    // Here you can add you firestore/ realtime database or merge the JSON if you want to batch write.
    console.log(jsn)
}

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!