Mit Sammlungen den Überblick behalten
Sie können Inhalte basierend auf Ihren Einstellungen speichern und kategorisieren.
Node.js Hello World
Dieses Codebeispiel ist eine "Hello World"-Anwendung, die auf Node.js ausgeführt wird. Das Beispiel veranschaulicht die folgenden Aufgaben:
Authentifizierung einrichten
Verbindung zu einer Bigtable-Instanz herstellen
Erstellen einer neuen Tabelle
Schreiben von Daten in die Tabelle
Lesen von Daten aus der Tabelle
Löschen einer Tabelle
Authentifizierung einrichten
Wenn Sie die Node.js -Beispiele auf dieser Seite in einer lokalen Entwicklungsumgebung verwenden möchten, installieren und initialisieren Sie die gcloud CLI und richten Sie dann die Standardanmeldedaten für Anwendungen mit Ihren Nutzeranmeldedaten ein.
Erstellen Sie ein neues Bigtable-Objekt, um eine Verbindung zu Bigtable herzustellen. Rufen Sie dann die Methode instance() auf, um das Objekt Instance abzurufen, das die Bigtable-Instanz darstellt.
Sie rufen die Methode table() der Instanz auf, um ein Table-Objekt abzurufen, das die Tabelle mit den Begrüßungen für "Hello World" darstellt. Wenn die Tabelle nicht vorhanden ist, rufen Sie die Methode create() der Tabelle auf. Damit erstellen Sie eine Tabelle mit einer einzigen Spaltenfamilie, die nur eine Version von jedem Wert enthält.
Mit einem Array aus Begrüßungsstrings erstellen Sie neue Zeilen für die Tabelle. Dazu rufen Sie die Methode map() des Arrays auf, um aus Objekten für Zeilen ein neues Array zu erstellen. Danach rufen Sie die Methode insert() der Tabelle auf, um der Tabelle die Zeilen hinzuzufügen.
console.log('Write some greetings to the table');constgreetings=['Hello World!','Hello Bigtable!','Hello Node!'];constrowsToInsert=greetings.map((greeting,index)=>({// Note: This example uses sequential numeric IDs for simplicity, but this// pattern can result in poor performance in a production application.// Rows are stored in sorted order by key, so sequential keys can result// in poor distribution of operations across nodes.//// For more information about how to design an effective schema for Cloud// Bigtable, see the documentation:// https://cloud.google.com/bigtable/docs/schema-designkey:`greeting${index}`,data:{[COLUMN_FAMILY_ID]:{[COLUMN_QUALIFIER]:{// Setting the timestamp allows the client to perform retries. If// server-side time is used, retries may cause multiple cells to// be generated.timestamp:newDate(),value:greeting,},},},}));awaittable.insert(rowsToInsert);
Filter erstellen
Erstellen Sie vor dem Lesen der von Ihnen geschriebenen Daten einen Filter, um die von Bigtable zurückgegebenen Daten zu beschränken. Mit diesem Filter wird Bigtable angewiesen, nur die neueste Zelle für jede Spalte zurückzugeben, auch wenn die Spalte ältere Zellen enthält.
constfilter=[{column:{cellLimit:1,// Only retrieve the most recent version of the cell.},},];
Zeile über ihren Zeilenschlüssel lesen
Mit der Methode row() der Tabelle rufen Sie einen Verweis auf die Zeile mit einem bestimmten Zeilenschlüssel ab. Rufen Sie dann die Methode get() der Zeile auf und übergeben den Filter, um nur eine Version von jedem Wert in dieser Zeile abzurufen.
console.log('Reading a single row by row key');const[singleRow]=awaittable.row('greeting0').get({filter});console.log(`\tRead: ${getRowGreeting(singleRow)}`);
Alle Tabellenzeilen scannen
Rufen Sie die Methode getRows() der Tabelle auf und übergeben Sie den Filter, um alle Zeilen in der Tabelle abzurufen. Durch Übergabe des Filters gibt Bigtable nur eine Version jedes Werts zurück.
console.log('Reading the entire table');// Note: For improved performance in production applications, call// `Table#readStream` to get a stream of rows. See the API documentation:// https://cloud.google.com/nodejs/docs/reference/bigtable/latest/Table#createReadStreamconst[allRows]=awaittable.getRows({filter});for(constrowofallRows){console.log(`\tRead: ${getRowGreeting(row)}`);}
Tabelle löschen
Mit der Methode delete() der Tabelle löschen Sie die Tabelle.
console.log('Delete the table');awaittable.delete();
Zusammenfassung
Im Folgenden ist das vollständige Codebeispiel ohne Kommentare aufgeführt.
const{Bigtable}=require('@google-cloud/bigtable');constTABLE_ID='Hello-Bigtable';constCOLUMN_FAMILY_ID='cf1';constCOLUMN_QUALIFIER='greeting';constINSTANCE_ID=process.env.INSTANCE_ID;if(!INSTANCE_ID){thrownewError('Environment variables for INSTANCE_ID must be set!');}constgetRowGreeting=row=>{returnrow.data[COLUMN_FAMILY_ID][COLUMN_QUALIFIER][0].value;};(async()=>{try{constbigtableClient=newBigtable();constinstance=bigtableClient.instance(INSTANCE_ID);consttable=instance.table(TABLE_ID);const[tableExists]=awaittable.exists();if(!tableExists){console.log(`Creating table ${TABLE_ID}`);constoptions={families:[{name:COLUMN_FAMILY_ID,rule:{versions:1,},},],};awaittable.create(options);}console.log('Write some greetings to the table');constgreetings=['Hello World!','Hello Bigtable!','Hello Node!'];constrowsToInsert=greetings.map((greeting,index)=>({key:`greeting${index}`,data:{[COLUMN_FAMILY_ID]:{[COLUMN_QUALIFIER]:{timestamp:newDate(),value:greeting,},},},}));awaittable.insert(rowsToInsert);constfilter=[{column:{cellLimit:1,// Only retrieve the most recent version of the cell.},},];console.log('Reading a single row by row key');const[singleRow]=awaittable.row('greeting0').get({filter});console.log(`\tRead: ${getRowGreeting(singleRow)}`);console.log('Reading the entire table');const[allRows]=awaittable.getRows({filter});for(constrowofallRows){console.log(`\tRead: ${getRowGreeting(row)}`);}console.log('Delete the table');awaittable.delete();}catch(error){console.error('Something went wrong:',error);}})();
[[["Leicht verständlich","easyToUnderstand","thumb-up"],["Mein Problem wurde gelöst","solvedMyProblem","thumb-up"],["Sonstiges","otherUp","thumb-up"]],[["Schwer verständlich","hardToUnderstand","thumb-down"],["Informationen oder Beispielcode falsch","incorrectInformationOrSampleCode","thumb-down"],["Benötigte Informationen/Beispiele nicht gefunden","missingTheInformationSamplesINeed","thumb-down"],["Problem mit der Übersetzung","translationIssue","thumb-down"],["Sonstiges","otherDown","thumb-down"]],["Zuletzt aktualisiert: 2025-09-04 (UTC)."],[[["\u003cp\u003eThis Node.js "hello world" sample demonstrates how to authenticate, connect to a Bigtable instance, and perform basic operations.\u003c/p\u003e\n"],["\u003cp\u003eThe sample uses the \u003ccode\u003e@google-cloud/bigtable\u003c/code\u003e module to connect to Bigtable and perform actions on a table.\u003c/p\u003e\n"],["\u003cp\u003eIt includes creating a new table with a specified column family if it doesn't exist, and inserting greeting strings as new rows.\u003c/p\u003e\n"],["\u003cp\u003eThe code shows how to filter data, read a specific row by its key, and scan all rows in the table, all while adhering to best practices.\u003c/p\u003e\n"],["\u003cp\u003eFinally, the sample application completes by deleting the created table.\u003c/p\u003e\n"]]],[],null,["Node.js hello world\n\nThis code sample is a \"hello world\" application that runs on Node.js. The sample\nillustrates how to complete the following tasks:\n\n- Set up authentication\n- Connect to a Bigtable instance.\n- Create a new table.\n- Write data to the table.\n- Read the data back.\n- Delete the table.\n\nSet up authentication\n\n\nTo use the Node.js samples on this page in a local\ndevelopment environment, install and initialize the gcloud CLI, and\nthen set up Application Default Credentials with your user credentials.\n\n1. [Install](/sdk/docs/install) the Google Cloud CLI.\n2. If you're using an external identity provider (IdP), you must first [sign in to the gcloud CLI with your federated identity](/iam/docs/workforce-log-in-gcloud).\n3. If you're using a local shell, then create local authentication credentials for your user account: \n\n```bash\ngcloud auth application-default login\n```\n4. You don't need to do this if you're using Cloud Shell.\n5. If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have [signed in to the gcloud CLI with your federated identity](/iam/docs/workforce-log-in-gcloud).\n\n\nFor more information, see\n[Set up authentication for a local development environment](/bigtable/docs/authentication#local-development).\n\nRunning the sample\n\nThis code sample uses the\n[Bigtable package](https://github.com/googleapis/nodejs-bigtable) of the\n[Google Cloud Client Library for Node.js](https://github.com/googleapis/google-cloud-node) to communicate with\nBigtable.\n\nTo run this sample program, follow the [instructions for the sample on\nGitHub](https://github.com/googleapis/nodejs-bigtable/tree/master/samples/hello-world).\n\nUsing the Cloud Client Library with Bigtable\n\nThe sample application connects to Bigtable and demonstrates some\nsimple operations.\n\nRequiring the client library\n\nThe sample requires the `@google-cloud/bigtable` module, which provides the\n[`Bigtable`](/nodejs/docs/reference/bigtable/latest/Bigtable) class. \n\n const {Bigtable} = require('https://cloud.google.com/nodejs/docs/reference/bigtable/latest/overview.html');\n\nConnecting to Bigtable\n\nTo connect to Bigtable, create a new\n[`Bigtable`](/nodejs/docs/reference/bigtable/latest/Bigtable) object. Then call its\n[`instance()`](/nodejs/docs/reference/bigtable/latest/Bigtable#instance) method to get an\n[`Instance`](/nodejs/docs/reference/bigtable/latest/Instance) object that represents your\nBigtable instance. \n\n const bigtableClient = new Bigtable();\n const instance = bigtableClient.instance(INSTANCE_ID);\n\nCreating a table\n\nCall the instance's [`table()`](/nodejs/docs/reference/bigtable/latest/Instance#table) method to get a\n[`Table`](/nodejs/docs/reference/bigtable/latest/Table) object that represents the table for \"hello world\"\ngreetings. If the table doesn't exist, call the table's\n[`create()`](/nodejs/docs/reference/bigtable/latest/Table#create) method to create a table with a single\ncolumn family that retains one version of each value.\n| **Note:** Columns that are related to one another are typically grouped into a column family. For more information about column families, see the [Bigtable\nstorage model](/bigtable/docs/overview#storage-model). \n\n const table = instance.table(TABLE_ID);\n const [tableExists] = await table.exists();\n if (!tableExists) {\n console.log(`Creating table ${TABLE_ID}`);\n const {BigtableTableAdminClient} = require('https://cloud.google.com/nodejs/docs/reference/bigtable/latest/overview.html').v2;\n const adminClient = new BigtableTableAdminClient();\n const projectId = await adminClient.getProjectId();\n await adminClient.createTable({\n parent: adminClient.instancePath(projectId, INSTANCE_ID),\n tableId: TABLE_ID,\n table: {\n columnFamilies: {\n [COLUMN_FAMILY_ID]: {\n gcRule: {\n maxNumVersions: 1,\n },\n },\n },\n },\n });\n }\n\nWriting rows to a table\n\nUse an array of greeting strings to create some new rows for the table: call the\narray's `map()` method to create a new array of objects that represent rows,\nthen call the table's [`insert()`](/nodejs/docs/reference/bigtable/latest/Table#insert) method to add the\nrows to the table. \n\n console.log('Write some greetings to the table');\n const greetings = ['Hello World!', 'Hello Bigtable!', 'Hello Node!'];\n const rowsToInsert = greetings.map((greeting, index) =\u003e ({\n // Note: This example uses sequential numeric IDs for simplicity, but this\n // pattern can result in poor performance in a production application.\n // Rows are stored in sorted order by key, so sequential keys can result\n // in poor distribution of operations across nodes.\n //\n // For more information about how to design an effective schema for Cloud\n // Bigtable, see the documentation:\n // https://cloud.google.com/bigtable/docs/schema-design\n key: `greeting${index}`,\n data: {\n [COLUMN_FAMILY_ID]: {\n [COLUMN_QUALIFIER]: {\n // Setting the timestamp allows the client to perform retries. If\n // server-side time is used, retries may cause multiple cells to\n // be generated.\n timestamp: new Date(),\n value: greeting,\n },\n },\n },\n }));\n await table.insert(rowsToInsert);\n\nCreating a filter\n\nBefore you read the data that you wrote, create a filter to limit the data that\nBigtable returns. This filter tells Bigtable to\nreturn only the most recent cell for each column, even if the column contains\nolder cells. \n\n const filter = [\n {\n column: {\n cellLimit: 1, // Only retrieve the most recent version of the cell.\n },\n },\n ];\n\nReading a row by its row key\n\nCall the table's [`row()`](/nodejs/docs/reference/bigtable/latest/Table#row) method to get a reference to\nthe row with a specific row key. Then call the row's\n[`get()`](/nodejs/docs/reference/bigtable/latest/Row#get) method, passing in the filter, to get one version\nof each value in that row. \n\n console.log('Reading a single row by row key');\n const [singleRow] = await table.row('greeting0').get({filter});\n console.log(`\\tRead: ${getRowGreeting(singleRow)}`);\n\nScanning all table rows\n\nCall the table's [`getRows()`](/nodejs/docs/reference/bigtable/latest/Table#getRows) method, passing in the\nfilter, to get all of the rows in the table. Because you passed in the filter,\nBigtable returns only one version of each value. \n\n console.log('Reading the entire table');\n // Note: For improved performance in production applications, call\n // `Table#readStream` to get a stream of rows. See the API documentation:\n // https://cloud.google.com/nodejs/docs/reference/bigtable/latest/Table#createReadStream\n const [allRows] = await table.getRows({filter});\n for (const row of allRows) {\n console.log(`\\tRead: ${getRowGreeting(row)}`);\n }\n\nDeleting a table\n\nDelete the table with the table's [`delete()`](/nodejs/docs/reference/bigtable/latest/Table#delete) method. \n\n console.log('Delete the table');\n await table.delete();\n\nPutting it all together\n\nHere is the full code sample without comments. \n\n\n\n\n const {Bigtable} = require('https://cloud.google.com/nodejs/docs/reference/bigtable/latest/overview.html');\n\n const TABLE_ID = 'Hello-Bigtable';\n const COLUMN_FAMILY_ID = 'cf1';\n const COLUMN_QUALIFIER = 'greeting';\n const INSTANCE_ID = process.env.INSTANCE_ID;\n\n if (!INSTANCE_ID) {\n throw new Error('Environment variables for INSTANCE_ID must be set!');\n }\n\n const getRowGreeting = row =\u003e {\n return row.data[COLUMN_FAMILY_ID][COLUMN_QUALIFIER][0].value;\n };\n\n (async () =\u003e {\n try {\n const bigtableClient = new Bigtable();\n const instance = bigtableClient.instance(INSTANCE_ID);\n\n const table = instance.table(TABLE_ID);\n const [tableExists] = await table.exists();\n if (!tableExists) {\n console.log(`Creating table ${TABLE_ID}`);\n const {BigtableTableAdminClient} = require('@google-cloud/bigtable').v2;\n const adminClient = new BigtableTableAdminClient();\n const projectId = await adminClient.getProjectId();\n await adminClient.createTable({\n parent: adminClient.instancePath(projectId, INSTANCE_ID),\n tableId: TABLE_ID,\n table: {\n columnFamilies: {\n [COLUMN_FAMILY_ID]: {\n gcRule: {\n maxNumVersions: 1,\n },\n },\n },\n },\n });\n }\n\n console.log('Write some greetings to the table');\n const greetings = ['Hello World!', 'Hello Bigtable!', 'Hello Node!'];\n const rowsToInsert = greetings.map((greeting, index) =\u003e ({\n key: `greeting${index}`,\n data: {\n [COLUMN_FAMILY_ID]: {\n [COLUMN_QUALIFIER]: {\n timestamp: new Date(),\n value: greeting,\n },\n },\n },\n }));\n await table.insert(rowsToInsert);\n\n const filter = [\n {\n column: {\n cellLimit: 1, // Only retrieve the most recent version of the cell.\n },\n },\n ];\n\n console.log('Reading a single row by row key');\n const [singleRow] = await table.row('greeting0').get({filter});\n console.log(`\\tRead: ${getRowGreeting(singleRow)}`);\n\n console.log('Reading the entire table');\n const [allRows] = await table.getRows({filter});\n for (const row of allRows) {\n console.log(`\\tRead: ${getRowGreeting(row)}`);\n }\n\n console.log('Delete the table');\n await table.delete();\n } catch (error) {\n console.error('Something went wrong:', error);\n }\n })();"]]