Node.js Quickstart

Complete the steps described in the rest of this page, and in about five minutes you'll have a simple Node.js command-line application that makes requests to the Google Apps Script Execution API.

Prerequisites

To run this quickstart, you'll need:

  • Node.js installed.
  • The npm package management tool (comes with Node.js).
  • Access to the internet and a web browser.
  • A Google account with Google Drive enabled.
  • A target Apps Script to call with the API.

Step 1: Turn on the Google Apps Script Execution API

  1. Open your target Apps Script in the editor and select Resources > Cloud Platform project.
  2. In the dialog that opens, click on the blue link (that starts with your script's name) at the top to open the console project associated with your script.
  3. The left sidebar should say API Manager. If it does not, click the icon in the upper-left to open a side panel and select API Manager. Select Library in the left sidebar.
  4. In the search bar under the Google APIs tab, enter "Google Apps Script Execution API". Click the same name in the list that appears. In the new tab that opens, click Enable API.
  5. Click Credentials in the left sidebar.
  6. Select the Credentials tab, click the Create credentials button and select OAuth client ID.
  7. Select the application type Other, enter the name "Google Apps Script Execution API Quickstart", and click the Create button.
  8. Click OK to dismiss the resulting dialog.
  9. Click the file_download (Download JSON) button to the right of the client ID.
  10. Move this file to your working directory and rename it client_secret.json.

Step 2: Install the client library

Run the following commands to install the libraries using npm:

npm install googleapis --save
npm install google-auth-library --save

Step 3: Set up the sample

Create a file named quickstart.js in your working directory and copy in the following code:



var fs = require('fs');
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');

// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/script-nodejs-quickstart.json
var SCOPES = ['https://www.googleapis.com/auth/drive'];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
    process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'script-nodejs-quickstart.json';

// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
  if (err) {
    console.log('Error loading client secret file: ' + err);
    return;
  }
  // Authorize a client with the loaded credentials, then call the
  // Google Apps Script Execution API.
  authorize(JSON.parse(content), callAppsScript);
});

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 *
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
  var clientSecret = credentials.installed.client_secret;
  var clientId = credentials.installed.client_id;
  var redirectUrl = credentials.installed.redirect_uris[0];
  var auth = new googleAuth();
  var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, function(err, token) {
    if (err) {
      getNewToken(oauth2Client, callback);
    } else {
      oauth2Client.credentials = JSON.parse(token);
      callback(oauth2Client);
    }
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 *
 * @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback to call with the authorized
 *     client.
 */
function getNewToken(oauth2Client, callback) {
  var authUrl = oauth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES
  });
  console.log('Authorize this app by visiting this url: ', authUrl);
  var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });
  rl.question('Enter the code from that page here: ', function(code) {
    rl.close();
    oauth2Client.getToken(code, function(err, token) {
      if (err) {
        console.log('Error while trying to retrieve access token', err);
        return;
      }
      oauth2Client.credentials = token;
      storeToken(token);
      callback(oauth2Client);
    });
  });
}

/**
 * Store token to disk be used in later program executions.
 *
 * @param {Object} token The token to store to disk.
 */
function storeToken(token) {
  try {
    fs.mkdirSync(TOKEN_DIR);
  } catch (err) {
    if (err.code != 'EEXIST') {
      throw err;
    }
  }
  fs.writeFile(TOKEN_PATH, JSON.stringify(token));
  console.log('Token stored to ' + TOKEN_PATH);
}

/**
 * Call an Apps Script function to list the folders in the user's root
 * Drive folder.
 *
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
function callAppsScript(auth) {
  var scriptId = 'ENTER_YOUR_SCRIPT_ID_HERE';
  var script = google.script('v1');

  // Make the API request. The request object is included here as 'resource'.
  script.scripts.run({
    auth: auth,
    resource: {
      function: 'getFoldersUnderRoot'
    },
    scriptId: scriptId
  }, function(err, resp) {
    if (err) {
      // The API encountered a problem before the script started executing.
      console.log('The API returned an error: ' + err);
      return;
    }
    if (resp.error) {
      // The API executed, but the script returned an error.

      // Extract the first (and only) set of error details. The values of this
      // object are the script's 'errorMessage' and 'errorType', and an array
      // of stack trace elements.
      var error = resp.error.details[0];
      console.log('Script error message: ' + error.errorMessage);
      console.log('Script error stacktrace:');

      if (error.scriptStackTraceElements) {
        // There may not be a stacktrace if the script didn't start executing.
        for (var i = 0; i < error.scriptStackTraceElements.length; i++) {
          var trace = error.scriptStackTraceElements[i];
          console.log('\t%s: %s', trace.function, trace.lineNumber);
        }
      }
    } else {
      // The structure of the result will depend upon what the Apps Script
      // function returns. Here, the function returns an Apps Script Object
      // with String keys and values, and so the result is treated as a
      // Node.js object (folderSet).
      var folderSet = resp.response.result;
      if (Object.keys(folderSet).length == 0) {
        console.log('No folders returned!');
      } else {
        console.log('Folders under your root folder:');
        Object.keys(folderSet).forEach(function(id){
          console.log('\t%s (%s)', folderSet[id], id);
        });
      }
    }

  });
}
Be sure to also replace the placeholder ENTER_YOUR_SCRIPT_ID_HERE with the script ID of your target script.

Step 4: Run the sample

Run the sample using the following command:

node quickstart.js

The first time you run the sample, it will prompt you to authorize access:

  1. Browse to the provided URL in your web browser.

    If you are not already logged into your Google account, you will be prompted to log in. If you are logged into multiple Google accounts, you will be asked to select one account to use for the authorization.

  2. Click the Accept button.
  3. Copy the code you're given, paste it into the command-line prompt, and press Enter.

Notes

  • Authorization information is stored on the file system, so subsequent executions will not prompt for authorization.
  • The authorization flow in this example is designed for a command line application. For information on how to perform authorization in other contexts, see the Authorizing and Authenticating. section of the library's README.

Further reading

发送以下问题的反馈:

此网页
Apps Script
Apps Script