// OK: await-ing a Promise before sending an HTTP responseawaitPromise.resolve();// WRONG: HTTP functions should send an// HTTP response instead of returning.returnPromise.resolve();// HTTP functions should signal termination by returning an HTTP response.// This should not be done until all background tasks are complete.res.send(200);res.end();// WRONG: this may not execute since an// HTTP response has already been sent.returnPromise.resolve();
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["難以理解","hardToUnderstand","thumb-down"],["資訊或程式碼範例有誤","incorrectInformationOrSampleCode","thumb-down"],["缺少我需要的資訊/範例","missingTheInformationSamplesINeed","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-09-04 (世界標準時間)。"],[],[],null,["# The Node.js runtime\n\nYour Cloud Run function runs in an environment consisting of an\noperating system version with add-on packages, language support, and the\n[Node.js Functions Framework](https://github.com/GoogleCloudPlatform/functions-framework-nodejs)\nlibrary that supports and invokes your function. This environment is\nidentified by the language version, and is known as the runtime ID.\n\nFunction preparation\n--------------------\n\nYou can prepare a function directly from the Google Cloud console or write it on\nyour local machine and upload it. To prepare your local machine for Node.js\ndevelopment, see [Set up a Node.js development environment](/nodejs/docs/setup).\n\nSupported Node.js runtimes and base images\n------------------------------------------\n\nSelect your runtime\n-------------------\n\nYou can select one of the supported Node.js runtimes for your function during\ndeployment.\n\n\nYou can select a runtime version using the Google Cloud console, or the\ngcloud CLI. Click the tab for instructions on using the tool of\nyour choice: \n\n### gcloud\n\nSpecify the [Node.js base image](/run/docs/configuring/services/runtime-base-images#how_to_obtain_base_images) for your function using the `--base-image` flag,\nwhile deploying your function. For example: \n\n gcloud run deploy \u003cvar translate=\"no\"\u003eFUNCTION\u003c/var\u003e \\\n --source . \\\n --function \u003cvar translate=\"no\"\u003eFUNCTION_ENTRYPOINT\u003c/var\u003e \\\n --base-image nodejs22\n\nReplace:\n\n- \u003cvar translate=\"no\"\u003eFUNCTION\u003c/var\u003e with the name of the function you are\n deploying. You can omit this parameter entirely,\n but you will be prompted for the name if you omit it.\n\n- \u003cvar translate=\"no\"\u003eFUNCTION_ENTRYPOINT\u003c/var\u003e with the entry point to your function in\n your source code. This is the code Cloud Run executes when your\n function runs. The value of this flag must be a function name or\n fully-qualified class name that exists in your source code.\n\nFor detailed instructions on deploying a function using the gcloud CLI, see [Deploy functions in Cloud Run](/run/docs/deploy-functions#gcloud).\n\n### Console\n\nYou can select a runtime version when you create or update a Cloud Run function in the Google Cloud console. For detailed\ninstructions on deploying a function, see [Deploy functions in Cloud Run](/run/docs/deploy-functions#deploy-functions).\n\nTo select a runtime in the Google Cloud console when you create a function, follow these steps:\n\n1. In the Google Cloud console, go to the Cloud Run page:\n\n [Go to Cloud Run](https://console.cloud.google.com/run)\n2. Click **Write a function**.\n\n3. In the **Runtime** list, select a Node.js runtime version.\n\n4. Click **Create**, and wait for Cloud Run to create the service\n using a placeholder revision.\n\n5. The console will redirect you to the **Source**\n tab where you can see the source code of your function. Click **Save and redeploy**.\n\nFor detailed instructions on updating the runtime version after your function is\ndeployed, see\n[Re-deploy new source code](/run/docs/deploy-functions#update-code-functions).\n\nSource code structure\n---------------------\n\nFor Cloud Run functions to find your function's definition, your\nsource code must follow a specific structure. See\n[Write Cloud Run functions](/static/run/docs/write-functions#node.js) for\nmore information.\n\nSpecify dependencies\n--------------------\n\nYou can specify dependencies for your functions by listing them in a\n`package.json` file. For more information, see\n[Specify dependencies in Node.js](/run/docs/runtimes/nodejs-dependencies).\n\nNPM build script\n----------------\n\nBy default, the Node.js runtime executes `npm run build` if a `build` script\nis detected in `package.json`. If you require additional control over your build\nsteps before starting your application, you can provide a [custom build step](/run/docs/building/functions)\nby adding a `gcp-build` script to your `package.json` file.\n\nYou can prevent your build from running the `npm run build` script by either:\n\n- Adding a `gcp-build` script with an empty value in your `package.json` file: `\"gcp-build\":\"\"`.\n\n- Setting the build environment variable `GOOGLE_NODE_RUN_SCRIPTS` to the empty string to prevent all scripts from running.\n\nAsynchronous function completion\n--------------------------------\n\nWhen working with asynchronous tasks that involve callbacks or `Promise`\nobjects, you must explicitly inform the runtime that your function has finished\nexecuting these tasks. You can do this in several different ways, as shown in\nthe following samples. The key is that your code must wait for the\nasynchronous task or `Promise` to complete before returning; otherwise the\nasynchronous component of your function may be terminated before it completes.\n\n### Event-driven functions\n\n**Implicit return** \n\n exports.implicitlyReturning = async (event, context) =\u003e {\n return await asyncFunctionThatReturnsAPromise();\n };\n\n**Explicit return** \n\n exports.explicitlyReturning = function (event, context) {\n return asyncFunctionThatReturnsAPromise();\n };\n\n### HTTP functions\n\n // OK: await-ing a Promise before sending an HTTP response\n await Promise.resolve();\n\n // WRONG: HTTP functions should send an\n // HTTP response instead of returning.\n return Promise.resolve();\n\n // HTTP functions should signal termination by returning an HTTP response.\n // This should not be done until all background tasks are complete.\n res.send(200);\n res.end();\n\n // WRONG: this may not execute since an\n // HTTP response has already been sent.\n return Promise.resolve();\n\n| **Warning:** failure to properly signal your function's termination may cause your function to either terminate early, or keep running until its timeout is reached.\n\nUse middleware to handle HTTP requests\n--------------------------------------\n\nNode.js HTTP functions provide `request` and `response`\nobjects that are compatible with [ExpressJS](https://expressjs.com/en/4x/api.html)\nto make consuming HTTP requests simpler. Cloud Run functions\nautomatically reads the request body, so you will always receive the body of a\nrequest independent of the media type. This means that HTTP requests should be\nconsidered to have been fully read by the time your code is executed. The\nnesting of ExpressJS apps should be used with this caveat---specifically,\nmiddleware that expects the body of a request to be unread might not behave as\nexpected.\n\nUse ES Modules\n--------------\n\nECMAScript modules (ES modules or ESM) are a TC39 standard, unflagged feature\nin Node version 14+ for loading JavaScript modules. Unlike CommonJS, ESM\nprovides an asynchronous API for loading modules. It also provides a popular\nsyntax improvement with `import` and `export` statements that can be used within\na Cloud Run function (instead of `require` statements).\n\nTo use ESM within a Cloud Run function, you must\ndeclare `\"type\": \"module\"` within your `package.json`. \n\n {\n ...\n \"type\": \"module\",\n ...\n }\n\nThen you can use `import` and `export` statements.\n\nLearn more about using [ES modules](https://github.com/GoogleCloudPlatform/functions-framework-nodejs/blob/master/docs/esm/README.md)."]]