0

I have a node.js script that works perfectly when running from command line, but when I try to use it as a function fails.

const functions = require('firebase-functions');
exports.dailyUpdate = functions.pubsub.schedule('5 5 * * *')
.onRun((context) => {
db.collection("meters")
  .get()
  .then(function (querySnapshot) {
    querySnapshot.forEach(function (doc) {
      let mtrList = meterlist.push([
        doc.id,
      ]);
      return true;
    });

    meterlist
      .forEach(function (obj) {
        var meterid = obj[0];
        var meterdata;
        var history = [];

        axios
          .get(url)
          .then((response) => {
            metername = meterid.toString();
            meterdata = response.data.meterdata;
            if (meterdata) {
              meterdata.forEach(function (obj) {
                let datadate = obj.stamp.substring(0, 10);
                let datatime = obj.stamp.substring(11, 13);
                let data = obj.data;
                history.push({
                  metername: metername,
                  datadate: datadate,
                  datatime: datatime,
                  data: data,
                });
              });

let todayUpdate = runCalculations(history);

               updateDB(todayUpdate);
            }
            return Promise.resolve("done!");
          })
          .catch(function (error) {
            console.log(error);
          });
        return true;
      })
    return true;
  })
  .catch(function (error) {
    console.log(error);
  });

  response.send("Updated!!");
});

I'm sure I'm doing something wrong, but when I, for example put the requires in the code section,

const axios = require("axios");
const firebase = require("firebase");
require("firebase/firestore");
var moment = require("moment");
var _ = require("lodash");
var Promise = require("promise");

doesn't run because it doesn't know where axios is. When I place them before the exports... below the const functions = require('firebase-functions'); I get different errors, including: ""Detailed stack trace: Error: Cannot find module 'axios'" // Provided module can't be loaded. // Could not load the function, shutting down. // Function cannot be initialized. "

The script itself runs a querySnapshot from a Firestore db, parses the results, calls an api through axios, runs a bunch of calculations, and then updates the db with the updated results. And I want this to run at 5:05AM every day.

I did not make any changes to the actual code of the script besides including the above exports code.

What am I missing?

6
  • What are the actual error messages you are seeing? You say you get errors but don't describe what the errors are. Commented Dec 11, 2020 at 15:44
  • Please edit the question to show the actual code and error messages. We need to see the complete minimal code that reproduces the issue. There should be enough information in the question that anyone can use to reproduce the issue. Commented Dec 11, 2020 at 15:48
  • Keep in mind also that you will almost certainly need to make changes to the code in order to ensure that the function terminates correctly. Don't just blindly copy everything in place - Cloud Functions has special requirements. Commented Dec 11, 2020 at 15:50
  • "Detailed stack trace: Error: Cannot find module 'axios'" // Provided module can't be loaded. // Could not load the function, shutting down. // Function cannot be initialized. Commented Dec 11, 2020 at 16:19
  • 1
    Did you use npm to install the modules you're using for this project? Commented Dec 12, 2020 at 17:05

1 Answer 1

2

When you deploy a Cloud Function, the node_modules directory needs to be populated, or you need to use Webpack (or some such) to include the dependencies. Firebase Deploy seems to essentially Zip the entire directory, upload and then run it in the cloud to deploy the specific function as called out in the entry point. All the dependencies need to be present in one form or another.

I happen to use a slightly unconventional approach to this, but the net-net is that Cloud Functions ARE NOT just another host to deploy to - they have quite specific formats and functions you need to follow. Read the documentation. Read it again. Walk through the samples. Then remember the samples are the simplest approach, but not the only approach.

Sign up to request clarification or add additional context in comments.

3 Comments

The Firebase CLI will not actually deploy node_modules at all. In fact, it deploys everything but that. Cloud Functions will reconstitute that before it creates a docker image for that function. It's essential that package.json and package-lock.json are up to date.
You would think that - but if the node_modules folder is not present, it will not deploy. How do I know? I just tried it. It might not upload the node_modules folder, but I immediately got a "module not found" when I ran firebase deploy after deleting the node_modules folder. might be because I use a somewhat unusual folder/deploy structure.
I'm not saying it doesn't have to be present on the local machine at the time of deployment. I'm just saying it doesn't get deployed. So when you said " Firebase Deploy seems to essentially Zip the entire directory", that's not really true.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.