e.iluf
e.iluf

Reputation: 1659

cloud function reads file but it's not returning the content on the client side

I am using the code below to read a json file in google firebase storage and then return the content of the file. The code works but all I am getting on the client side is null

exports.updateProductCatalogue = functions.https.onCall(async (data, context) => {
const filepath = data.filepath
const bucketname = data.bucket

const remoteFile = bucket.file("storeid.json");

let buffer = '';
remoteFile.createReadStream()
.on('error', function(err) {console.log(err)})
.on('data', function(response) {
    buffer += response
    console.log(buffer)

})
.on('end', function() {
    //console.log(buffer);
 console.log("FINISHED!!")
 
})

  return buffer
})

this is my client side js call

function getUpdatedCatalogue(){
var getStorageData = firebase.functions().httpsCallable('updateProductCatalogue');
var callData = {

"bucket":"test"
}
getStorageData(callData).then(function(result){
console.log(result)

}).catch(function(error){
console.log(error)

})
}

The cloud console.log is showing that the content is read and shown in log but client side console.log is returning null. Here is the file file i am reading.

Why am I not getting the file content returned and displayed on client side? how can I fix this?

Upvotes: 0

Views: 78

Answers (1)

Eranga Heshan
Eranga Heshan

Reputation: 5804

The problem is that you're returning the buffer before the stream finishes reading the file.

Try this (not tested),


exports.updateProductCatalogue = functions.https.onCall(async (data, context) => {
  const filepath = data.filepath;
  const bucketname = data.bucket;

  const remoteFile = bucket.file("storeid.json");

  return new Promise(resolve, reject) => {
    let buffer = '';

    remoteFile.createReadStream()
    .on('error', function(err) {
      console.log(err);
      reject(err);
    })
    .on('data', function(response) {
      buffer += response;
      console.log(buffer);
    })
    .on('end', function() {
      console.log("FINISHED!!")
      resolve(buffer);
    });
  });
});

Upvotes: 1

Related Questions