Red Root
Red Root

Reputation: 111

Firebase function file.download returns undefined

I am trying to parse excel file and store the data into firestore. But before that I need to download the file. I am getting an error when dowloading the file into temp folder in google cloud storage. Here is the code:

import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
import * as os from "os";
import {join} from "path";
import {existsSync, mkdirSync} from "fs";

const fh = functions.storage.object();
export const helloWorld = fh.onFinalize((object) => {
  const path = join(os.tmpdir(), object.name??"");
  if (!existsSync(os.tmpdir())) {
    mkdirSync(os.tmpdir());
  }
  console.log(object.bucket);
  functions.logger.log("triggered");
  functions.logger.log(path);
  if (!admin.apps.length) {
    admin.initializeApp();
  }
  const bkt = admin.storage().bucket(object.bucket);
  const file = bkt.file(object.name??"");
  const prom = file.download({destination: path});
  prom.then((p) => {
    functions.logger.log(p.length);
  });
});

Here is the error

12:00:58.525 PM
helloWorld
<id>.appspot.com
12:00:58.525 PM
helloWorld
triggered 
12:00:58.525 PM
helloWorld
/tmp/communal_2019.xlsx
12:00:58.875 PM
helloWorld
Function returned undefined, expected Promise or value
12:00:58.880 PM
helloWorld
Function execution took 555 ms, finished with status: 'ok'

Upvotes: 0

Views: 269

Answers (1)

Red Root
Red Root

Reputation: 111

After some hours, I figured out that the file is downloaded and is in the wanted location. I just needed to make it sync using await.

import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
import * as os from "os";
import {join} from "path";
import {existsSync, mkdirSync} from "fs";

const fh = functions.storage.object();
export const helloWorld = fh.onFinalize(async (object) => {
  const path = join(os.tmpdir(), object.name??"");
  if (!existsSync(os.tmpdir())) {
    mkdirSync(os.tmpdir());
  }
  console.log(object.bucket);
  functions.logger.log("triggered");
  functions.logger.log(path);
  if (!admin.apps.length) {
    admin.initializeApp();
  }
  const bkt = admin.storage().bucket(object.bucket);
  const file = bkt.file(object.name??"");
  await file.download({destination: path});
  // I can access my file using its path here
});

Upvotes: 1

Related Questions