만들기를 클릭하고 Cloud Run이 자리표시자 버전을 사용해서 서비스를 만들 때까지 기다립니다.
콘솔이 함수의 소스 코드를 볼 수 있는 소스로 리디렉션됩니다. 저장 및 재배포를 클릭합니다.
함수가 배포된 후 런타임 버전을 업데이트하는 방법에 대한 자세한 내용은 새 소스 코드 재배포를 참조하세요.
소스 코드 구조
Cloud Run Functions에서 함수 정의를 찾으려면 소스 코드가 특정 구조를 따라야 합니다. 자세한 내용은 Cloud Run Functions 작성을 참고하세요.
종속 항목 지정
함수에 대한 종속 항목을 지정하는 방법은 package.json 파일에 나열하는 것입니다. 자세한 내용은 Node.js의 종속 항목 지정을 참조하세요.
NPM 빌드 스크립트
기본적으로 build 스크립트가 package.json에서 감지되면 Node.js 런타임이 npm run build를 실행합니다. 애플리케이션을 시작하기 전에 빌드 단계를 추가로 제어해야 하면 gcp-build 스크립트를 package.json 파일에 추가하여 커스텀 빌드 단계를 제공하면 됩니다.
다음 중 하나를 수행하여 빌드가 npm run build 스크립트를 실행하지 않도록 할 수 있습니다.
값이 비어 있는 gcp-build 스크립트를 package.json 파일에 추가합니다.
"gcp-build":""
빌드 환경 변수 GOOGLE_NODE_RUN_SCRIPTS를 빈 문자열로 설정하여 모든 스크립트가 실행되지 않도록 합니다.
비동기 함수 완성
콜백 또는 Promise 객체가 포함된 비동기 작업을 수행할 때는 함수가 이러한 작업의 실행을 완료했음을 런타임에 명시적으로 알려야 합니다. 다음 샘플과 같이 여러 방법으로 이 작업을 수행할 수 있습니다. 핵심은 코드가 비동기 작업 또는 Promise가 완료될 때까지 기다린 후에 반환되어야 한다는 것입니다. 그렇지 않으면 함수의 비동기 구성요소가 완료되기 전에 종료될 수 있습니다.
// 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();
미들웨어를 사용하여 HTTP 요청 처리
Node.js HTTP 함수는 ExpressJS와 호환되는 request 및 response 객체를 제공하여 HTTP 요청을 간단히 사용할 수 있도록 합니다. Cloud Run 함수는 자동으로 요청 본문을 읽으므로, 사용자는 미디어 유형과 관계없이 항상 요청 본문을 받습니다. 즉, 코드가 실행될 때 HTTP 요청을 완전히 읽은 것으로 간주합니다. 이러한 점에 주의하여 ExpressJS 앱의 중첩을 사용해야 합니다. 특히 요청 본문이 읽히지 않을 것으로 예상하는 미들웨어는 제대로 동작하지 않을 수 있습니다.
ES 모듈 사용
ECMAScript 모듈(ES 모듈 또는 ESM)은 자바스크립트 모듈 로드를 위한 Node 버전 14이상에서 플래그 지정되지 않은 TC39 표준 기능입니다. CommonJS와 달리 ESM은 모듈 로드를 위해 비동기 API를 제공합니다. 또한 require 문 대신 Cloud Run 함수 내에서 사용될 수 있는 import 및 export 문으로 인기 있는 문법 개선 사항을 제공합니다.
Cloud Run 함수 내에서 ESM을 사용하려면 package.json 내에서 "type": "module"을 선언해야 합니다.
[[["이해하기 쉬움","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-07-15(UTC)"],[],[],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)."]]