我该怎样在一个Node.js Google Cloud函数中使用单独的.js文件?

huangapple go评论79阅读模式
英文:

How do I use a separate .js file within a node.js Google Cloud function?

问题

我明白了,以下是您提供的内容的翻译:

我正在尝试使用 node.js 运行时编写一个 Google Cloud 函数该函数只需返回附带的 .js 文件中存储的函数的结果

我的实际函数涉及更多内容因此我在下面写了一个非常基本的示例来说明我想要的效果

这是函数产生一个简单的 HTMLHello World!”问候语存储在 function.js 
```javascript
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';

// 使用 Functions Framework 向已部署函数的端点发出 HTTP 请求时,注册一个将执行的 HTTP 函数。
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"。

构建失败,状态:FAILURE,消息:(node:122) 警告:要加载 ES 模块,请在 package.json 中设置 "type":"module",或使用 .mjs 扩展名。

然后,如果我这样做,我会收到一个部署错误,说容器没有正确设置。

无法创建或更新 Cloud Run 服务 function-1,容器健康检查失败。修订版 'function...' 尚未准备就绪,无法提供流量。用户提供的启动和侦听端口由 PORT=8080 环境变量提供。

我相信问题在于我如何“require”(或者没有要求)function.js 文件。通过我的试错测试(交替和同时尝试带有和不带有 export 前缀的函数,使用 res.sendFile,尝试将 myFunction() 的结果存储为常量等等),我可以在 Chrome 开发者工具中看到,当函数部署时,它实际上不会加载 function.js 文件。您可以在下面的函数 GUI 中看到该文件存在,但我唯一能“使用”它的方式是使用 res.sendFile(但然后它只返回代码的文本,而不是代码的结果)。

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

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

我觉得答案就在我的眼前,但我找不到它。还有其他人做过类似的事情吗?


<details>
<summary>英文:</summary>

I am trying to write a Google Cloud Function using the node.js runtime that simply returns the **result** of a function stored in an accompanying .js file.

My real function is bit more involved, so I&#39;ve written a *very* rudimentary example below to illustrate what I&#39;m after.

This is the function, producing a simple HTML &quot;Hello World!&quot; greeting, stored in **function.js**.

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


This is the **index.js** script, which I want to just *respond* with the result of *myfunction()* noted above.

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());
});


And the accompanying **Package.json** below without &quot;type&quot;:&quot;module&quot; included for illustration.

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



If I try to deploy the function as shown above, the deployment fails and tells me I should update the package.json to include &quot;type&quot;:&quot;module&quot;. 

&gt; Build failed with status: FAILURE and message: (node:122) Warning: To load an ES module, set &quot;type&quot;:&quot;module&quot; in the package.json. or us the .mjs extension.

And then if I do that I get a deployment error saying that the container isn&#39;t set up properly. 

&gt; Could not create or update Cloud Run service function-1, Container Healthcheck failed.  Revision &#39;function...&#39; is not ready and cannot serve traffic.  The user-provided start and listen on the port defined provided by the PORT=8080 environment variable.

I believe the issue is in how I am &quot;requiring&quot; (or not requiring) the **function.js** file.  From my trial-and-error testing (alternatively and concurrently trying the function with and without export prefix, using res.sendFile, trying to store the myfunction() result as a const...)I can see in Chrome developer tools that when the function does deploy it doesn&#39;t actually load the function.js file with it. You can see in the Function gui below that the file is there, but the only way I can &quot;use&quot; it is if I do res.sendFile (but then it just returns the text of the code, not the result of the code. [![enter image description here](https://i.stack.imgur.com/xasrf.png)](https://i.stack.imgur.com/xasrf.png)

In effect, I want the Google Cloud function to *behave* as if it&#39;s written like this...

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


I feel like the answer is staring me in the face but I can&#39;t find it.  Has anyone else done something like this before?


</details>


# 答案1
**得分**: 0

以下是您要翻译的内容:

"这个问题的答案已被删除,所以我在这里发布解决方案,以防将来有人需要。package.json 没有进行任何更改,但需要更新 Cloud Run 函数的权限(https://stackoverflow.com/a/76015948/21749472)。

**index.js**

```javascript
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>'
}
英文:

The answer to this question was deleted, so posting the solution here in case it helps someone in the future. No changes made to package.json, and the cloud run function permissions needed to be updated (https://stackoverflow.com/a/76015948/21749472).

index.js

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

functions.http(&#39;helloHttp&#39;, (req, res) =&gt; {
  res.send(myfunction());
});

function.js

module.exports = function myFunction() {
  return &#39;&lt;!DOCTYPE html&gt;&lt;html&gt;&lt;body&gt;&lt;h1&gt;Hello World&lt;/h1&gt;&lt;p&gt;&#127758;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;&#39;
}

huangapple
  • 本文由 发表于 2023年5月18日 04:12:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76275887.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定