Node.js hello world
This code sample is a "hello world" application that runs on Node.js. The sample illustrates how to complete the following tasks:
- Set up authentication
- Connect to a Bigtable instance.
- Create a new table.
- Write data to the table.
- Read the data back.
- Delete the table.
Set up authentication
To use the Node.js samples on this page in a local development environment, install and initialize the gcloud CLI, and then set up Application Default Credentials with your user credentials.
- Install the Google Cloud CLI.
-
To initialize the gcloud CLI, run the following command:
gcloud init
-
If you're using a local shell, then create local authentication credentials for your user account:
gcloud auth application-default login
You don't need to do this if you're using Cloud Shell.
For more information, see Set up authentication for a local development environment.
Running the sample
This code sample uses the Bigtable package of the Google Cloud Client Library for Node.js to communicate with Bigtable.
To run this sample program, follow the instructions for the sample on GitHub.
Using the Cloud Client Library with Bigtable
The sample application connects to Bigtable and demonstrates some simple operations.
Requiring the client library
The sample requires the @google-cloud/bigtable
module, which provides the
Bigtable
class.
Connecting to Bigtable
To connect to Bigtable, create a new
Bigtable
object. Then call its
instance()
method to get an
Instance
object that represents your
Bigtable instance.
Creating a table
Call the instance's table()
method to get a
Table
object that represents the table for "hello world"
greetings. If the table doesn't exist, call the table's
create()
method to create a table with a single
column family that retains one version of each value.
Writing rows to a table
Use an array of greeting strings to create some new rows for the table: call the
array's map()
method to create a new array of objects that represent rows,
then call the table's insert()
method to add the
rows to the table.
Creating a filter
Before you read the data that you wrote, create a filter to limit the data that Bigtable returns. This filter tells Bigtable to return only the most recent cell for each column, even if the column contains older cells.
Reading a row by its row key
Call the table's row()
method to get a reference to
the row with a specific row key. Then call the row's
get()
method, passing in the filter, to get one version
of each value in that row.
Scanning all table rows
Call the table's getRows()
method, passing in the
filter, to get all of the rows in the table. Because you passed in the filter,
Bigtable returns only one version of each value.
Deleting a table
Delete the table with the table's delete()
method.
Putting it all together
Here is the full code sample without comments.