Mantieni tutto organizzato con le raccolte
Salva e classifica i contenuti in base alle tue preferenze.
Hello World Node.js
Questo esempio di codice è un'applicazione "Hello World" che viene eseguita su Node.js. L'esempio
mostra come completare le seguenti attività:
Configura l'autenticazione
Connettiti a un'istanza Bigtable.
Crea una nuova tabella.
Scrivere i dati nella tabella.
Leggi i dati.
Elimina la tabella.
Configura l'autenticazione
Per utilizzare gli esempi di Node.js questa pagina in un ambiente di sviluppo locale, installa e inizializza gcloud CLI, quindi configura le credenziali predefinite dell'applicazione con le tue credenziali utente.
Per connetterti a Bigtable, crea un nuovo oggetto
Bigtable. Quindi chiama il metodo
instance() per ottenere un
oggetto Instance che rappresenta la tua
istanza Bigtable.
Chiama il metodo table() dell'istanza per ottenere un oggetto Table che rappresenta la tabella per i saluti "Hello world". Se la tabella non esiste, chiama il metodo create() della tabella per creare una tabella con una singola famiglia di colonne che conserva una versione di ogni valore.
Utilizza un array di stringhe di saluto per creare nuove righe per la tabella: chiama il metodo map() dell'array per creare un nuovo array di oggetti che rappresentano le righe, quindi chiama il metodo insert() della tabella per aggiungere le righe alla tabella.
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);
Creare un filtro
Prima di leggere i dati che hai scritto, crea un filtro per limitare i dati restituiti da Bigtable. Questo filtro indica a Bigtable di restituire solo la cella più recente per ogni colonna, anche se la colonna contiene celle meno recenti.
constfilter=[{column:{cellLimit:1,// Only retrieve the most recent version of the cell.},},];
Lettura di una riga in base alla chiave di riga
Chiama il metodo row() della tabella per ottenere un riferimento alla riga con una chiave di riga specifica. Poi chiama il metodo
get() della riga, passando il filtro, per ottenere una versione
di ogni valore in quella riga.
console.log('Reading a single row by row key');const[singleRow]=awaittable.row('greeting0').get({filter});console.log(`\tRead: ${getRowGreeting(singleRow)}`);
Scansione di tutte le righe della tabella
Chiama il metodo getRows() della tabella, passando il filtro, per ottenere tutte le righe della tabella. Poiché hai passato il filtro,
Bigtable restituisce una sola versione di ogni valore.
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)}`);}
Eliminazione di una tabella
Elimina la tabella con il metodo delete() della tabella.
console.log('Delete the table');awaittable.delete();
In sintesi
Ecco l'esempio di codice completo senza commenti.
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);}})();
[[["Facile da capire","easyToUnderstand","thumb-up"],["Il problema è stato risolto","solvedMyProblem","thumb-up"],["Altra","otherUp","thumb-up"]],[["Difficile da capire","hardToUnderstand","thumb-down"],["Informazioni o codice di esempio errati","incorrectInformationOrSampleCode","thumb-down"],["Mancano le informazioni o gli esempi di cui ho bisogno","missingTheInformationSamplesINeed","thumb-down"],["Problema di traduzione","translationIssue","thumb-down"],["Altra","otherDown","thumb-down"]],["Ultimo aggiornamento 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===================\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\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------------------\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--------------------------------------------\n\nThe sample application connects to Bigtable and demonstrates some\nsimple operations.\n\n### Requiring 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\n### Connecting 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\n### Creating 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 options = {\n families: [\n {\n name: COLUMN_FAMILY_ID,\n rule: {\n versions: 1,\n },\n },\n ],\n };\n await table.create(options);\n }\n\n### Writing 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\n### Creating 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\n### Reading 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\n### Scanning 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\n### Deleting 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-----------------------\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 options = {\n families: [\n {\n name: COLUMN_FAMILY_ID,\n rule: {\n versions: 1,\n },\n },\n ],\n };\n await table.create(options);\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 })();"]]