คู่มือเริ่มต้นใช้งาน Node.js ฉบับย่อ

ทำตามขั้นตอนที่อธิบายไว้ในส่วนที่เหลือของหน้านี้ แล้วคุณจะมีแอปพลิเคชันบรรทัดคำสั่ง Node.js อย่างง่ายที่ส่งคำขอไปยัง YouTube Data API ในเวลาประมาณ 5 นาที

โค้ดตัวอย่างที่ใช้ในคู่มือนี้จะดึงข้อมูลทรัพยากร channel สำหรับช่อง YouTube ของ GoogleDevelopers และพิมพ์ข้อมูลพื้นฐานบางอย่างจากทรัพยากรนั้น

ข้อกำหนดเบื้องต้น

หากต้องการเรียกใช้ Quickstart นี้ คุณจะต้องมีสิ่งต่อไปนี้

  • ติดตั้ง Node.js แล้ว
  • เครื่องมือจัดการแพ็กเกจ npm (มาพร้อมกับ Node.js)
  • สิทธิ์เข้าถึงอินเทอร์เน็ตและเว็บเบราว์เซอร์
  • บัญชี Google

ขั้นตอนที่ 1: เปิดใช้ YouTube Data API

  1. ใช้วิซาร์ดนี้เพื่อสร้างหรือเลือกโปรเจ็กต์ใน Google Developers Console และเปิดใช้ API โดยอัตโนมัติ คลิกต่อไป แล้ว ไปที่ข้อมูลเข้าสู่ระบบ

  2. ในหน้าสร้างข้อมูลเข้าสู่ระบบ ให้คลิกปุ่ม ยกเลิก

  3. เลือกแท็บหน้าจอขอความยินยอม OAuth ที่ด้านบนของหน้า เลือกอีเมล ป้อนชื่อสินค้า หากยังไม่ได้ตั้งค่า แล้วคลิกปุ่มบันทึก

  4. เลือกแท็บข้อมูลเข้าสู่ระบบ คลิกปุ่มสร้างข้อมูลเข้าสู่ระบบ แล้วเลือกรหัสไคลเอ็นต์ OAuth

  5. เลือกประเภทแอปพลิเคชันอื่นๆ ป้อนชื่อ "YouTube Data API Quickstart" แล้วคลิกปุ่มสร้าง

  6. คลิกตกลง เพื่อปิดกล่องโต้ตอบที่ปรากฏขึ้น

  7. คลิกปุ่ม (ดาวน์โหลด JSON) ทางด้านขวาของรหัสไคลเอ็นต์

  8. ย้ายไฟล์ที่ดาวน์โหลดไปยังไดเรกทอรีงานและเปลี่ยนชื่อเป็น client_secret.json

ขั้นตอนที่ 2: ติดตั้งไลบรารีของไคลเอ็นต์

เรียกใช้คำสั่งต่อไปนี้เพื่อติดตั้งไลบรารีโดยใช้ npm

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

ขั้นตอนที่ 3: ตั้งค่าตัวอย่าง

สร้างไฟล์ชื่อ quickstart.js ในไดเรกทอรีงานแล้วคัดลอกโค้ดต่อไปนี้ลงในไฟล์

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);
    }
  });
}

ขั้นตอนที่ 4: เรียกใช้ตัวอย่าง

เรียกใช้ตัวอย่างโดยใช้คำสั่งต่อไปนี้

node quickstart.js

เมื่อเรียกใช้ตัวอย่างเป็นครั้งแรก ระบบจะแจ้งให้คุณให้สิทธิ์เข้าถึง

  1. เปิด URL ที่ให้ไว้ในเว็บเบราว์เซอร์

    หากยังไม่ได้เข้าสู่ระบบบัญชี Google ระบบจะแจ้งให้คุณเข้าสู่ระบบ หากคุณเข้าสู่ระบบบัญชี Google หลายบัญชี ระบบจะขอให้คุณเลือกบัญชีที่จะใช้ในการให้สิทธิ์

  2. คลิกปุ่มยอมรับ
  3. คัดลอกโค้ดที่ได้รับ วางลงในพรอมต์บรรทัดคำสั่ง แล้วกด Enter

หมายเหตุ

อ่านเพิ่มเติม