Dickson Afful
Dickson Afful

Reputation: 838

How to create a file in the cloud function and upload to a bucket

For some time now, I've been trying to create a file (sample.txt) containing some text (hello world) and finally uploading it into a bucket. Is there a way I can implement this?. My attempted code is below:

exports.uploadFile = functions.https.onCall(async (data, context) => {
  try {
    const tempFilePath = path.join(os.tmpdir(), "sample.txt");

    await fs.writeFile(tempFilePath, "hello world");
    const bucket = await admin.storage().bucket("allcollection");

    await bucket.upload(tempFilePath);
    return fs.unlinkSync(tempFilePath);
  } catch (error) {
    console.log(error);
    throw new functions.https.HttpsError(error);
  }
});

Anytime this code is run I get and error like this in there firebase console:

TypeError [ERR_INVALID_CALLBACK]: Callback must be a function 
 at maybeCallback (fs.js:128:9) 
  at Object.writeFile (fs.js:1163:14) 

Upvotes: 0

Views: 114

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317467

You're not using fs.writeFile() correctly. As you can see from the linked documentation, it takes 3 or 4 arguments, one being a callback. The error message is saying you didn't pass a callback. On top of that, it doesn't return a promise, so you can't effectively await it. Consider using fs.writeFileSync() instead to make this easier.

Upvotes: 1

Related Questions