Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Node.js Hello World
Esse exemplo de código é um aplicativo "hello world" que é executado no Node.js. Ela mostra como concluir as seguintes tarefas:
Configurar a autenticação
Conecte a uma instância do Bigtable.
criar uma nova tabela;
Gravação de dados na tabela
Leitura dos dados
Exclusão da tabela
Configurar a autenticação
Para usar os exemplos Node.js desta página em um
ambiente de desenvolvimento local, instale e inicialize a CLI gcloud e
configure o Application Default Credentials com suas credenciais de usuário.
Para se conectar ao Bigtable, crie um novo
objeto Bigtable. Em seguida,
chame o método instance() para receber um
objeto Instance que representa sua
instância do Bigtable.
Chame o método table() da instância para receber um objeto Table que represente a tabela para saudações "hello world". Se a tabela não existir, chame o método create() da tabela para criar uma tabela com um único grupo de colunas que mantenha uma versão de cada valor.
Use uma matriz de strings de saudação para criar algumas linhas novas na tabela. Para isso, chame o método map() da matriz para criar uma nova matriz de objetos que representem linhas e, em seguida, chame o método insert() para adicionar as linhas à tabela.
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);
Como criar um filtro
Antes de ler os dados que você gravou, crie um filtro para limitar os dados que o Bigtable retorna. Com esse filtro, o Bigtable
retornará apenas a célula mais recente de cada coluna, mesmo que ela contenha
células mais antigas.
constfilter=[{column:{cellLimit:1,// Only retrieve the most recent version of the cell.},},];
Como ler uma linha pela chave dela
Chame o método row() da tabela para receber uma referência à linha com uma chave de linha específica. Em seguida, chame o método get() da linha, passando o filtro, para receber uma versão de cada valor nessa linha.
console.log('Reading a single row by row key');const[singleRow]=awaittable.row('greeting0').get({filter});console.log(`\tRead: ${getRowGreeting(singleRow)}`);
Como verificar todas as linhas da tabela
Chame o método getRows() da tabela, transmitindo o filtro, para receber todas as linhas na tabela. Como você transmitiu no filtro,
o Bigtable retornará apenas uma versão de cada valor.
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)}`);}
console.log('Delete the table');awaittable.delete();
Como tudo funciona em conjunto
Veja o exemplo de código completo sem comentários.
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);}})();
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 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 })();"]]