Using the Node.js Client Libraries

This document demonstrates how to use the Google Cloud Platform Node.js client libraries for Google Compute Engine to authorize requests and to list Compute Engine virtual machine instances. This sample also describes how to use the gcloud-node and google-api-nodejs-client libraries to access Compute Engine resources from both outside and inside a virtual machine instance. This document does not discuss how to build and run applications within a virtual machine instance.

For a full list of available client libraries, including other Google client libraries and third-party open source libraries, see the Client Libraries page.

Contents

  1. Prerequisites
  2. Getting Started with Google Cloud client library
    1. Authorizing Request
    2. Initializing the API
    3. Listing Instances
  3. Getting Started with Google API client library
    1. Authorizing Request
    2. Initializing the API
    3. Listing Instances

Prerequisites

Cloud Project

Create a project on the Google Cloud Platform Console and enable billing.. The project contains all of your resources under a single namespace, and billing is required to create any instances in your project.

Cloud SDK

The Cloud SDK contains tools and libraries that enable you to easily create and manage resources on Google Cloud Platform. Please refer to the Cloud SDK installation instructions to get the SDK for your platform.

After installing the SDK, authenticate and set your default project:

gcloud init

Getting Started with the Google Cloud Client Library for Node.js

The gcloud-node library as the recommended idiomatic way of accessing and interacting with Google Cloud services. Use the Google Cloud client library over the Google API client library whenever possible. The typical installation is simply:

$ npm install gcloud

The purpose of this exercise is to describe how to authorize requests and how to perform a basic operational task Google Cloud Node.js client library.

Authorizing Requests

This sample uses OAuth 2.0 authorization. There are many ways to authorize requests using OAuth 2.0, but for the example, you will use Application Default Credentials. This allows you to re-use the credentials from the gcloud tool. You should have installed and authorized this tool in the Prerequisites section.

// By default, the client will authenticate using the service account file
// specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable and use
// the project specified by the GCLOUD_PROJECT environment variable. See
// https://googlecloudplatform.github.io/gcloud-node/#/docs/google-cloud/latest/guides/authentication
var Compute = require('@google-cloud/compute');

Initializing the API

Before you can make requests, you first need to initialize an instance of the Google Compute Engine service:

// Instantiate a compute client
var compute = Compute();

Listing Instances

Now that you have an authorized instance, the client you can use the client to make calls to the Google Compute Engine API.

To list the instances in your project, call compute.getVMs():

/**
 * @param {Function} callback Callback function.
 */
function getVmsExample (callback) {
  // In this example we only want one VM per page
  var options = {
    maxResults: 1
  };
  compute.getVMs(options, function (err, vms) {
    if (err) {
      return callback(err);
    }

    console.log('VMs:', vms);
    callback(null, vms);
  });
}

The complete example:

'use strict';

// By default, the client will authenticate using the service account file
// specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable and use
// the project specified by the GCLOUD_PROJECT environment variable. See
// https://googlecloudplatform.github.io/gcloud-node/#/docs/google-cloud/latest/guides/authentication
var Compute = require('@google-cloud/compute');

// Instantiate a compute client
var compute = Compute();

/**
 * @param {Function} callback Callback function.
 */
function getVmsExample (callback) {
  // In this example we only want one VM per page
  var options = {
    maxResults: 1
  };
  compute.getVMs(options, function (err, vms) {
    if (err) {
      return callback(err);
    }

    console.log('VMs:', vms);
    callback(null, vms);
  });
}

Getting Started with the Google API Client library for Node.js

The google-api-nodejs-client library contains the core Node.js library for accessing Google APIs and also contains the OAuth 2.0 client library. This library is low-level wrapper for Google REST APIs, for a more idiomatic way of accessing Google Cloud Platfrom APIs, use the gcloud-node library. The typical installation is simply:

$ npm install googleapis

The purpose of this exercise is to describe how to authorize requests and how to perform a basic operational task Google API Node.js client library.

Authorizing Requests

This sample uses OAuth 2.0 authorization. There are many ways to authorize requests using OAuth 2.0, but for the example you will use Application Default Credentials. This allows you to re-use the credentials from the gcloud tool. You should have installed and authorized this tool in the prerequisites section.

function auth (callback) {
  google.auth.getApplicationDefault(function (err, authClient) {
    if (err) {
      return callback(err);
    }

    // The createScopedRequired method returns true when running on GAE or a
    // local developer machine. In that case, the desired scopes must be passed
    // in manually. When the code is  running in GCE or a Managed VM, the scopes
    // are pulled from the GCE metadata server.
    // See https://cloud.google.com/compute/docs/authentication for more
    // information.
    if (authClient.createScopedRequired && authClient.createScopedRequired()) {
      // Scopes can be specified either as an array or as a single,
      // space-delimited string.
      authClient = authClient.createScoped([
        'https://www.googleapis.com/auth/cloud-platform',
        'https://www.googleapis.com/auth/compute',
        'https://www.googleapis.com/auth/compute.readonly'
      ]);
    }
    callback(null, authClient);
  });
}

Initializing the API

Before you can make requests, you first need to initialize an instance of the Google Compute Engine service:

var google = require('googleapis');
var compute = google.compute('v1');

Listing Instances

Now that you have an authorized instance the client you can use the client to make calls to the Google Compute Engine API.

To list the instances in your project, call compute.getVMs():

/**
 * @param {Function} callback Callback function.
 */
function getVmsExample (callback) {
  auth(function (err, authClient) {
    if (err) {
      return callback(err);
    }
    // Retrieve the vms
    compute.instances.aggregatedList({
      auth: authClient,
      project: process.env.GCLOUD_PROJECT,
      // In this example we only want one VM per page
      maxResults: 1
    }, function (err, vms) {
      if (err) {
        return callback(err);
      }

      console.log('VMs:', vms);
      callback(null, vms);
    });
  });
}

The complete example:

var google = require('googleapis');
var compute = google.compute('v1');

function auth (callback) {
  google.auth.getApplicationDefault(function (err, authClient) {
    if (err) {
      return callback(err);
    }

    // The createScopedRequired method returns true when running on GAE or a
    // local developer machine. In that case, the desired scopes must be passed
    // in manually. When the code is  running in GCE or a Managed VM, the scopes
    // are pulled from the GCE metadata server.
    // See https://cloud.google.com/compute/docs/authentication for more
    // information.
    if (authClient.createScopedRequired && authClient.createScopedRequired()) {
      // Scopes can be specified either as an array or as a single,
      // space-delimited string.
      authClient = authClient.createScoped([
        'https://www.googleapis.com/auth/cloud-platform',
        'https://www.googleapis.com/auth/compute',
        'https://www.googleapis.com/auth/compute.readonly'
      ]);
    }
    callback(null, authClient);
  });
}

/**
 * @param {Function} callback Callback function.
 */
function getVmsExample (callback) {
  auth(function (err, authClient) {
    if (err) {
      return callback(err);
    }
    // Retrieve the vms
    compute.instances.aggregatedList({
      auth: authClient,
      project: process.env.GCLOUD_PROJECT,
      // In this example we only want one VM per page
      maxResults: 1
    }, function (err, vms) {
      if (err) {
        return callback(err);
      }

      console.log('VMs:', vms);
      callback(null, vms);
    });
  });
}

Send feedback about...

Compute Engine Documentation