Jika Anda membuat fungsi baru, lihat Panduan Memulai Konsol di Cloud Run. Konten di halaman ini hanya berlaku untuk fungsi lama yang sudah ada yang dibuat dengan Cloud Functions v1 API.
Tetap teratur dengan koleksi
Simpan dan kategorikan konten berdasarkan preferensi Anda.
Membuat dan men-deploy fungsi Cloud Run HTTP menggunakan Node.js (generasi ke-1)
Panduan ini akan memandu Anda dalam proses penulisan fungsi Cloud Run menggunakan runtime Node.js. Ada dua jenis fungsi Cloud Run:
Fungsi HTTP, yang Anda panggil dari permintaan HTTP standar.
Fungsi berbasis peristiwa, yang Anda gunakan untuk menangani peristiwa dari infrastruktur Cloud, seperti pesan di topik Pub/Sub, atau perubahan dalam bucket Cloud Storage.
Contoh ini menunjukkan cara membuat fungsi HTTP sederhana.
Sebelum memulai
Sign in to your Google Cloud account. If you're new to
Google Cloud,
create an account to evaluate how our products perform in
real-world scenarios. New customers also get $300 in free credits to
run, test, and deploy workloads.
In the Google Cloud console, on the project selector page,
select or create a Google Cloud project.
Buat direktori di sistem lokal Anda untuk kode fungsi:
Linux atau Mac OS X
mkdir ~/helloworld
cd ~/helloworld
Windows
mkdir %HOMEPATH%\helloworld
cd %HOMEPATH%\helloworld
Buat file index.js di direktori helloworld dengan
konten berikut:
constfunctions=require('@google-cloud/functions-framework');constescapeHtml=require('escape-html');/** * Responds to an HTTP request using data from the request body parsed according * to the "content-type" header. * * @param {Object} req Cloud Function request context. * @param {Object} res Cloud Function response context. */functions.http('helloHttp',(req,res)=>{res.send(`Hello ${escapeHtml(req.query.name||req.body.name||'World')}!`);});
Fungsi contoh ini mengambil nama yang diberikan dalam permintaan HTTP dan menampilkan salam, atau "Halo Dunia!" jika tidak ada nama yang diberikan.
Menentukan dependensi
Dependensi pada Node.js disimpan dalam file bernama package.json.
Anda dapat membuat file ini secara manual atau dengan perintah npm.
Untuk membuat file dependensi package.json menggunakan npm, jalankan perintah berikut:
[[["Mudah dipahami","easyToUnderstand","thumb-up"],["Memecahkan masalah saya","solvedMyProblem","thumb-up"],["Lainnya","otherUp","thumb-up"]],[["Sulit dipahami","hardToUnderstand","thumb-down"],["Informasi atau kode contoh salah","incorrectInformationOrSampleCode","thumb-down"],["Informasi/contoh yang saya butuhkan tidak ada","missingTheInformationSamplesINeed","thumb-down"],["Masalah terjemahan","translationIssue","thumb-down"],["Lainnya","otherDown","thumb-down"]],["Terakhir diperbarui pada 2025-09-03 UTC."],[[["\u003cp\u003eThis guide explains how to create and deploy an HTTP Cloud Run function using Node.js, which can be triggered by standard HTTP requests.\u003c/p\u003e\n"],["\u003cp\u003eThe process involves setting up your development environment, creating an \u003ccode\u003eindex.js\u003c/code\u003e file with the function code, and specifying dependencies in a \u003ccode\u003epackage.json\u003c/code\u003e file.\u003c/p\u003e\n"],["\u003cp\u003eThe sample function provided in the guide takes a name from the HTTP request and returns a personalized greeting, or "Hello World!" if no name is given.\u003c/p\u003e\n"],["\u003cp\u003eYou can deploy the function using the \u003ccode\u003egcloud\u003c/code\u003e CLI, including the option to allow unauthenticated access, and subsequently test it by accessing the function's URL.\u003c/p\u003e\n"],["\u003cp\u003eLogs for the deployed function can be viewed via the \u003ccode\u003egcloud\u003c/code\u003e CLI or the Cloud Logging UI, allowing you to monitor the function's execution and identify any issues.\u003c/p\u003e\n"]]],[],null,["# Quickstart: Create and deploy a HTTP Cloud Run function by using Node.js (1st gen)\n\nCreate and deploy an HTTP Cloud Run function by using\nNode.js (1st gen)\n=======================================================================\n\nThis guide takes you through the process of writing a Cloud Run function\nusing the Node.js runtime. There are two types of Cloud Run functions:\n\n- An HTTP function, which you invoke from standard HTTP requests.\n- An event-driven function, which you use to handle events from your Cloud infrastructure, such as messages on a Pub/Sub topic, or changes in a Cloud Storage bucket.\n\nThe sample shows how to create a simple HTTP function.\n| **Learn more** : For more details, read about [HTTP functions](/functions/1stgendocs/writing/write-http-functions) and [event-driven functions](/functions/1stgendocs/writing/write-event-driven-functions).\n\nBefore you begin\n----------------\n\n- Sign in to your Google Cloud account. If you're new to Google Cloud, [create an account](https://console.cloud.google.com/freetrial) to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.\n- In the Google Cloud console, on the project selector page,\n select or create a Google Cloud project.\n\n | **Note**: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.\n\n [Go to project selector](https://console.cloud.google.com/projectselector2/home/dashboard)\n-\n [Verify that billing is enabled for your Google Cloud project](/billing/docs/how-to/verify-billing-enabled#confirm_billing_is_enabled_on_a_project).\n\n-\n\n\n Enable the Cloud Functions and Cloud Build APIs.\n\n\n [Enable the APIs](https://console.cloud.google.com/flows/enableapi?apiid=cloudfunctions,cloudbuild.googleapis.com&redirect=https://cloud.google.com/functions/1stgendocs/create-deploy-http-nodejs-1st-gen)\n\n- In the Google Cloud console, on the project selector page,\n select or create a Google Cloud project.\n\n | **Note**: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.\n\n [Go to project selector](https://console.cloud.google.com/projectselector2/home/dashboard)\n-\n [Verify that billing is enabled for your Google Cloud project](/billing/docs/how-to/verify-billing-enabled#confirm_billing_is_enabled_on_a_project).\n\n-\n\n\n Enable the Cloud Functions and Cloud Build APIs.\n\n\n [Enable the APIs](https://console.cloud.google.com/flows/enableapi?apiid=cloudfunctions,cloudbuild.googleapis.com&redirect=https://cloud.google.com/functions/1stgendocs/create-deploy-http-nodejs-1st-gen)\n\n1. [Install and initialize the gcloud CLI](/sdk/docs).\n2. Update and install `gcloud` components: \n\n ```bash\n gcloud components update\n ```\n| **Note** : Need a command prompt? You can use the [Cloud Shell](https://console.cloud.google.com/?cloudshell=true). The Cloud Shell is a command line environment that already includes the Google Cloud CLI, so you don't need to install it. The Google Cloud CLI also comes preinstalled on Google Compute Engine Virtual Machines.\n3. Prepare your development environment.\n [Go to the Node.js setup guide](/nodejs/docs/setup)\n\nCreate a function\n-----------------\n\n1. Create a directory on your local system for the function code:\n\n ### Linux or Mac OS X\n\n mkdir ~/helloworld\n cd ~/helloworld\n\n ### Windows\n\n mkdir %HOMEPATH%\\helloworld\n cd %HOMEPATH%\\helloworld\n\n2. Create an `index.js` file in the `helloworld` directory with the\n following contents:\n\n const functions = require('@google-cloud/functions-framework');\n const escapeHtml = require('escape-html');\n\n /**\n * Responds to an HTTP request using data from the request body parsed according\n * to the \"content-type\" header.\n *\n * @param {Object} req Cloud Function request context.\n * @param {Object} res Cloud Function response context.\n */\n functions.http('helloHttp', (req, res) =\u003e {\n res.send(`Hello ${escapeHtml(req.query.name || req.body.name || 'World')}!`);\n });\n\n This example function takes a name supplied in the HTTP request and returns\n a greeting, or \"Hello World!\" when no name is supplied.\n | **Note:** Cloud Run functions looks for deployable functions in `index.js` by default. Use the [`--source`](/sdk/gcloud/reference/functions/deploy#--source) flag when [deploying your function via `gcloud`](#deploying_the_function) to specify a different directory containing an `index.js` file.\n\nSpecify dependencies\n--------------------\n\nDependencies in Node.js are stored in a file called\n[`package.json`](https://docs.npmjs.com/files/package.json).\nYou can create this file manually or with the\n[npm](https://docs.npmjs.com/) command.\n\n- To create your `package.json` dependency file by using `npm`, run these\n commands:\n\n npm init\n npm install c8 gaxios mocha sinon supertest wait-port --save-dev\n npm install @google-cloud/functions-framework escape-html\n\n- If you prefer to build your `package.json`file manually, create a `package.json`\n file in the `helloworld` directory with the following contents:\n\n {\n \"name\": \"nodejs-docs-samples-functions-hello-world-http\",\n \"version\": \"0.0.1\",\n \"private\": true,\n \"license\": \"Apache-2.0\",\n \"author\": \"Google Inc.\",\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git\"\n },\n \"engines\": {\n \"node\": \"\u003e=16.0.0\"\n },\n \"scripts\": {\n \"unit-test\": \"c8 mocha -p -j 2 test/index.test.js test/*unit*test.js test/*integration*test.js --timeout=6000 --exit\",\n \"system-test\": \"c8 mocha -p -j 2 test/*system*test.js --timeout=600000 --exit\",\n \"all-test\": \"npm run unit-test && npm run system-test\",\n \"test\": \"npm -- run unit-test\"\n },\n \"dependencies\": {\n \"@google-cloud/functions-framework\": \"^3.1.0\",\n \"escape-html\": \"^1.0.3\"\n },\n \"devDependencies\": {\n \"c8\": \"^10.0.0\",\n \"gaxios\": \"^6.0.0\",\n \"mocha\": \"^10.0.0\",\n \"sinon\": \"^18.0.0\",\n \"supertest\": \"^7.0.0\",\n \"wait-port\": \"^1.0.4\"\n }\n }\n\n | **Note:** Node.js client libraries are available for a variety of Google Cloud products, and can be installed as dependencies. See the list [here](https://github.com/googleapis/google-cloud-node#google-cloud-nodejs-client-libraries).\n\n| **Learn more** : For more details, read about [specifying dependencies](/functions/1stgendocs/writing/specifying-dependencies-nodejs).\n\nDeploy the function\n-------------------\n\nTo deploy the function with an HTTP trigger, run the following\ncommand in the `helloworld` directory: \n\n gcloud functions deploy helloHttp --no-gen2 --runtime nodejs20 --trigger-http --allow-unauthenticated\n\nThe `--allow-unauthenticated` flag lets you reach the function\n[without authentication](/functions/1stgendocs/securing/managing-access-iam#allowing_unauthenticated_http_function_invocation).\nTo require\n[authentication](/functions/1stgendocs/securing/authenticating#developers), omit the\nflag.\n| **Learn more** : For more details, read about [deploying\n| Cloud Run functions](/functions/1stgendocs/deploy#basics).\n\nTest the function\n-----------------\n\n1. When the function finishes deploying, take note of the `httpsTrigger.url`\n property or find it using the following command:\n\n gcloud functions describe helloHttp\n\n It should look like this: \n\n ```\n https://GCP_REGION-PROJECT_ID.cloudfunctions.net/helloHttp\n ```\n2. Visit this URL in your browser. You should see a \"Hello World!\" message.\n\n Try passing a name in the HTTP request, for example by using the following\n URL: \n\n ```\n https://GCP_REGION-PROJECT_ID.cloudfunctions.net/helloHttp?name=NAME\n ```\n\n You should see the message \"Hello \u003cvar translate=\"no\"\u003eNAME\u003c/var\u003e!\"\n\nView logs\n---------\n\nLogs for Cloud Run functions are viewable using the Google Cloud CLI, and in the\nCloud Logging UI.\n\n### Use the command-line tool\n\nTo view logs for your function with the gcloud CLI, use the\n[`logs read`](/sdk/gcloud/reference/functions/logs/read) command, followed by\nthe name of the function: \n\n```bash\ngcloud functions logs read helloHttp\n```\n\nThe output should resemble the following: \n\n```bash\nLEVEL NAME EXECUTION_ID TIME_UTC LOG\nD helloHttp rvb9j0axfclb 2019-09-18 22:06:25.983 Function execution started\nD helloHttp rvb9j0axfclb 2019-09-18 22:06:26.001 Function execution took 19 ms, finished with status code: 200\n```\n| **Note:** There is typically a slight delay between when log entries are created and when they show up in Cloud Logging.\n\n### Use the Logging dashboard\n\nYou can also view logs for Cloud Run functions from the\n[Google Cloud console](https://console.cloud.google.com/project/_/logs?service=cloudfunctions.googleapis.com).\n| **Learn more** : For more details, read about [writing, viewing,\n| and responding to logs](/functions/1stgendocs/monitoring/logging)."]]