如何在node.js Google Cloud函数中使用单独的.js文件?

kadbb459  于 2023-05-28  发布在  Node.js
关注(0)|答案(1)|浏览(177)

我正在尝试使用node.js运行时编写一个Google Cloud Function,它只是返回存储在附带的.js文件中的函数的result
我真实的的功能有点复杂,所以我写了一个非常基本的例子来说明我所追求的。
这是一个函数,生成一个简单的HTML“Hello World!“greeting,存放在function.js中。

export function myFunction() {
  return '<!DOCTYPE html><html><body><h1>Hello World</h1><p>🌎</p></body></html>'
}

这是index.js脚本,我想用上面提到的 myfunction() 的结果来 * 响应 *。

const functions = require('@google-cloud/functions-framework');
import { myfunction } from '/workspace/function.js'

// Register an HTTP function with the Functions Framework that will be executed
// when you make an HTTP request to the deployed function's endpoint.
functions.http('helloGET', (req, res) => {
  res.send(myfunction());
});

以及下面附带的Package.json(不含“type”:“module”)用于说明。

{
  "name": "json-test",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@google-cloud/functions-framework": "^3.0.0"
  }
}

如果我尝试如上所示部署函数,部署失败,并告诉我应该更新package.json以包含“type”:“module”。
生成失败,状态为:失败和消息:(节点:122)警告:要加载ES模块,请在package.json中设置“type”:“module”。或使用.mjs扩展名。
如果我这样做,我会得到一个部署错误,说容器没有正确设置。
无法创建或更新Cloud Run服务函数-1,容器运行状况检查失败。修订版“功能...”未就绪,无法为流量提供服务。用户提供的启动和侦听由PORT=8080环境变量提供的端口。
我认为问题在于我如何“要求”(或不要求)function.js文件。从我的试错测试(交替地和同时地尝试带和不带导出前缀的函数,使用res.sendFile,尝试将myfunction()结果存储为const...)中,我可以在Chrome开发者工具中看到,当函数部署时,它实际上并没有加载带有它的function.js文件。你可以在下面的Function gui中看到这个文件,但是我可以“使用”它的唯一方法是我执行res.sendFile(但是它只返回代码的文本,而不是代码的结果。

实际上,我希望Google Cloud函数的行为就像这样写的一样......

functions.http('helloGET', (req, res) => {
  res.send('<!DOCTYPE html><html><body><h1>Hello World</h1><p>🌎</p></body></html>');
});

我觉得答案就在眼前,但我找不到。以前有人做过这样的事吗?

bf1o4zei

bf1o4zei1#

这个问题的答案被删除了,所以在这里发布解决方案,以防将来对某人有帮助。package.json未更改,需要更新云运行函数权限(https://stackoverflow.com/a/76015948/21749472)。

index.js

const functions = require('@google-cloud/functions-framework');
const myfunction = require('./function.js')

functions.http('helloHttp', (req, res) => {
  res.send(myfunction());
});

function.js

module.exports = function myFunction() {
  return '<!DOCTYPE html><html><body><h1>Hello World</h1><p>🌎</p></body></html>'
}

相关问题