Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
Hello World en Node.js
Esta muestra de código es una aplicación “hello world” que se ejecuta en Node.js. En este ejemplo, se muestra cómo completar las siguientes tareas:
Configura la autenticación
Conéctate a una instancia de Bigtable.
Crear una tabla nueva
Escribir datos en la tabla
Volver a leer datos
Borrar la tabla
Configura la autenticación
Para usar las muestras de Node.js de esta página en un entorno de desarrollo
local, instala e inicializa gcloud CLI y, luego,
configura las credenciales predeterminadas de la aplicación con tus credenciales de usuario.
Para conectarte a Bigtable, crea un objeto Bigtable nuevo. Luego, llama a su método instance() para obtener un objeto Instance que represente tu instancia de Bigtable.
Llama al método table() de la instancia para obtener un objeto Table que represente la tabla de saludos de "hello world". Si la tabla no existe, llama al método create() de la tabla a fin de crear una tabla con una sola familia de columnas que conserve una versión de cada valor.
Usa un arreglo de strings de saludos para crear algunas filas nuevas para la tabla: llama al método map() del arreglo para crear un nuevo arreglo de objetos que represente filas y, luego, llama al método insert() de la tabla para agregar las filas a la tabla.
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);
Crea un filtro
Antes de leer los datos que escribiste, crea un filtro para limitar los datos que muestre Bigtable. El filtro le indica a Bigtable que muestre solo la celda más reciente de cada columna, incluso si contiene celdas más antiguas.
constfilter=[{column:{cellLimit:1,// Only retrieve the most recent version of the cell.},},];
Lee una fila por su clave de fila
Llama al método row() de la tabla para obtener una referencia de la fila con una clave de fila específica. Luego, llama al método get() de la fila, y aplica el filtro para obtener una versión de cada valor en esa fila.
console.log('Reading a single row by row key');const[singleRow]=awaittable.row('greeting0').get({filter});console.log(`\tRead: ${getRowGreeting(singleRow)}`);
Analiza todas las filas de una tabla
Llama al método getRows() de la tabla, y aplica el filtro para obtener todas las filas de la tabla. Dado que aplicaste el filtro, Bigtable solo mostrará una versión 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();
Revisión general
El código de muestra completo sin comentarios.
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 comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 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 })();"]]