Append serialized rows to a BigQuery table using a write stream.

## Code sample

### Node.js


Before trying this sample, follow the Node.js setup instructions in the
[BigQuery quickstart using
client libraries](https://docs.cloud.google.com/bigquery/docs/quickstarts/quickstart-client-libraries).


For more information, see the
[BigQuery Node.js API
reference documentation](https://googleapis.dev/nodejs/bigquery/latest/index.html).


To authenticate to BigQuery, set up Application Default Credentials.
For more information, see

[Set up authentication for client libraries](https://docs.cloud.google.com/bigquery/docs/authentication.md.txt#client-libs).

```javascript
'use strict';

const {BigQueryWriteClient, adapt} = require('@google-cloud/bigquery-storage');
const {status} = require('@grpc/grpc-js');
const protobuf = require('protobufjs');

const client = new BigQueryWriteClient();

/**
 * Use the appendRows method
 *
 * @param {string} projectId - The Google Cloud project ID (for example, 'example-project-id').
 * @param {string} datasetId - The BigQuery dataset ID (for example, 'example_dataset').
 * @param {string} tableId - The BigQuery table ID (for example, 'example_table').
 * @param {string} streamId - ID of the write stream (server-generated stream ID from CreateWriteStream, or '_default' for the table's default stream).
 */
async function appendRows(projectId, datasetId, tableId, streamId) {
  try {
    const writeStream = `projects/${projectId}/datasets/${datasetId}/tables/${tableId}/streams/${streamId}`;

    // Define the schema for the serialized rows
    const root = protobuf.Root.fromJSON({
      nested: {
        CustomerRecord: {
          fields: {
            customerName: {
              type: 'string',
              id: 1,
            },
            rowNum: {
              type: 'int64',
              id: 2,
            },
          },
        },
      },
    });

    const CustomerRecord = root.lookupType('CustomerRecord');
    const descriptor = CustomerRecord.toDescriptor('proto2');
    const protoDescriptor = adapt.normalizeDescriptor(descriptor);

    // Serialize sample rows matching the schema
    const row = {
      customerName: 'example-customer',
      rowNum: 1,
    };
    const serializedRow = CustomerRecord.encode(row).finish();

    // Construct the append rows request with schema and rows
    const request = {
      writeStream,
      protoRows: {
        writerSchema: {
          protoDescriptor,
        },
        rows: {
          serializedRows: [serializedRow],
        },
      },
    };

    // Open bidirectional stream and register handlers
    const stream = client.appendRows();

    const appendPromise = new Promise((resolve, reject) => {
      stream.on('data', response => {
        if (response.error) {
          reject(new Error(response.error.message));
          return;
        }
        resolve(response);
      });
      stream.on('error', reject);
    });

    stream.write(request);
    stream.end();

    const response = await appendPromise;
    console.log(`Successfully appended rows to: ${writeStream}`);
    if (response.appendResult && response.appendResult.offset) {
      console.log(`Append result offset: ${response.appendResult.offset}`);
    }
  } catch (err) {
    if (err.code !== undefined && Object.values(status).includes(err.code)) {
      console.error(`BigQuery Storage API error (code ${err.code}):`, err.message);
    } else {
      throw err;
    }
  }
}

module.exports = { appendRows };
```

## What's next


To search and filter code samples for other Google Cloud products, see the
[Google Cloud sample browser](https://docs.cloud.google.com/docs/samples.md.txt?product=bigquery).