我正在研究用于发送推送通知的Firebase服务器端代码。为了使代码简洁,我决定将一些函数移到我创建并称为notificationFunctions.js的另一个类中。

当我在const notificationFunctions = require('notificationFunctions');顶部执行index.js并从sendNotification函数中调用该函数时,将项目部署到云时会出现错误:

⚠  functions[sendNotifications]: Deployment error.
Build failed: exit status 1
npm ERR! Linux 4.4.0-108-generic
npm ERR! argv "/nodejs/bin/node" "/nodejs/bin/npm" "--global-style" "--production" "--fetch-retries=5" "--fetch-retry-factor=2" "--fetch-retry-mintimeout=1000" "install" "/workspace"
npm ERR! node v6.11.5
npm ERR! npm  v3.10.10
npm ERR! code E404

npm ERR! 404 Registry returned 404 for GET on https://registry.npmjs.org/notificationFunctions
npm ERR! 404
npm ERR! 404  'notificationFunctions' is not in the npm registry.
npm ERR! 404 Your package name is not valid, because
npm ERR! 404  1. name can no longer contain capital letters
npm ERR! 404 It was specified as a dependency of 'functions'
npm ERR! 404
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.

npm ERR! Please include the following file with any support request:
npm ERR!     /workspace/npm-debug.log



Functions deploy had errors. To continue deploying other features (such as database), run:
    firebase deploy --except functions


我还在"notificationFunctions": "1.0.0"中添加了package.json并将自定义功能移至node_modules文件夹。

向Firebase NodeJS添加自定义类的正确方法是什么?

编辑:

当我遵循道格·史蒂文森(Doug Stevenson)的建议并且从package.json中删除​​自定义类并将该类移到与index.js相同的目录时,我仍然不断收到错误消息:

i  deploying functions
i  functions: ensuring necessary APIs are enabled...
✔  functions: all necessary APIs are enabled
i  functions: preparing functions directory for uploading...

Error: Error parsing triggers: Cannot find module 'notificationFunctions'

Try running "npm install" in your functions directory before deploying.


编辑2

好。我认为必须更改将类导入到require('./notificationFunctions')的方式,这可以消除部署项目时的所有错误。

但是,一旦在云上运行代码,就会出现以下错误:FIREBASE WARNING: Exception was thrown by user callback. TypeError: notificationFunctions.getNotificationPayload is not a function

我从代码中调用函数的方式是:const payload = notificationFunctions.getNotificationPayload(userLanguage, senderName, groupName, messageContent, messageType);

最佳答案

如果将代码添加到functions文件夹中的项目中,则无需对package.json依赖项进行任何更改。只有发布到NPM registry的模块才需要npm依赖项。

您的构建现在正在做的是在NPM上寻找一个名为“ notificationFunctions”的节点模块,而该模块显然不存在。您应该将模块代码以及所有其他代码放在functions下,然后直接从require()放置。

另外,请记住,node_modules不会随您的代码一起部署。 Cloud Functions将在服务器端获取所有npm依赖项,并使它们可用于您的代码。

10-08 17:04