Guía de inicio rápido de Node.js

Completa los pasos que se describen en el resto de esta página y, en unos cinco minutos, tendrás una aplicación de línea de comandos básica de Node.js que realiza solicitudes a la API de YouTube Data.

El código de muestra que se usa en esta guía recupera el recurso channel para el canal de YouTube de GoogleDevelopers y muestra información básica de ese recurso.

Requisitos previos

Para ejecutar esta guía de inicio rápido, necesitarás lo siguiente:

  • Node.js instalado
  • La herramienta de administración de paquetes npm (viene con Node.js)
  • Acceso a Internet y un navegador web
  • Una Cuenta de Google

Paso 1: Activa la API de YouTube Data

  1. Usa este asistente para crear o seleccionar un proyecto en Google Developers Console y activar automáticamente la API. Haz clic en Continue y, luego, en Go to credentials.

  2. En la página Create credentials, haz clic en el botón Cancel.

  3. En la parte superior de la página, selecciona la pestaña pantalla de consentimiento de OAuth. Selecciona una dirección de correo electrónico, ingresa un nombre del producto si aún no está configurado y haz clic en el botón Save.

  4. Selecciona la pestaña Credentials, haz clic en el botón Create credentials y selecciona ID de cliente de OAuth.

  5. Selecciona el tipo de aplicación Other, ingresa el nombre "API de YouTube Data Quickstart" y haz clic en el botón Create.

  6. Haz clic en OK para descartar el diálogo resultante.

  7. Haz clic en el botón (Descargar JSON) a la derecha del ID de cliente.

  8. Mueve el archivo descargado a tu directorio de trabajo y cámbiale el nombre a client_secret.json.

Paso 2: Instala la biblioteca cliente

Ejecuta los siguientes comandos para instalar las bibliotecas con npm:

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

Paso 3: Configura la muestra

Crea un archivo llamado quickstart.js en tu directorio de trabajo y copia el siguiente código:

var fs = require('fs');
var readline = require('readline');
var {google} = require('googleapis');
var OAuth2 = google.auth.OAuth2;

// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/youtube-nodejs-quickstart.json
var SCOPES = ['https://www.googleapis.com/auth/youtube.readonly'];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
    process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'youtube-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 YouTube API.
  authorize(JSON.parse(content), getChannel);
});

/**
 * 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 oauth2Client = new 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), (err) => {
    if (err) throw err;
    console.log('Token stored to ' + TOKEN_PATH);
  });
}

/**
 * Lists the names and IDs of up to 10 files.
 *
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
function getChannel(auth) {
  var service = google.youtube('v3');
  service.channels.list({
    auth: auth,
    part: 'snippet,contentDetails,statistics',
    forUsername: 'GoogleDevelopers'
  }, function(err, response) {
    if (err) {
      console.log('The API returned an error: ' + err);
      return;
    }
    var channels = response.data.items;
    if (channels.length == 0) {
      console.log('No channel found.');
    } else {
      console.log('This channel\'s ID is %s. Its title is \'%s\', and ' +
                  'it has %s views.',
                  channels[0].id,
                  channels[0].snippet.title,
                  channels[0].statistics.viewCount);
    }
  });
}

Paso 4: Ejecuta la muestra

Ejecuta la muestra con el siguiente comando:

node quickstart.js

La primera vez que ejecutes la muestra, se te solicitará que autorices el acceso:

  1. Navega a la URL proporcionada en tu navegador web.

    Si aún no accediste a tu Cuenta de Google, se te solicitará que lo hagas. Si accediste a varias Cuentas de Google, se te pedirá que selecciones una para usar en la autorización.

  2. Haz clic en el botón Accept.
  3. Copia el código que recibiste, pégalo en el símbolo del sistema y presiona Intro.

Notas

  • La información de autorización se almacena en el sistema de archivos, por lo que las ejecuciones posteriores no solicitarán autorización.
  • El flujo de autorización en este ejemplo está diseñado para una aplicación de línea de comandos. Para obtener información sobre cómo realizar la autorización en una aplicación web que usa la API de YouTube Data, consulta Cómo usar OAuth 2.0 para aplicaciones de servidor web.

    Para obtener información sobre cómo realizar la autorización en otros contextos, consulta la sección Authorizing and Authenticating del archivo README de la biblioteca.

Lecturas adicionales