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

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

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

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

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

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

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

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

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

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

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

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

  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

หมายเหตุ

  • ระบบจะจัดเก็บข้อมูลการให้สิทธิ์ไว้ในระบบไฟล์ ดังนั้นการดำเนินการครั้งต่อๆ ไป จะไม่แจ้งให้ขอสิทธิ์
  • ขั้นตอนการให้สิทธิ์ในตัวอย่างนี้ออกแบบมาสำหรับแอปพลิเคชันบรรทัดคำสั่ง ดูข้อมูลเกี่ยวกับวิธีให้สิทธิ์ในเว็บแอปพลิเคชันที่ใช้ YouTube Data API ได้ที่การใช้ OAuth 2.0 สำหรับแอปพลิเคชันเว็บเซิร์ฟเวอร์

    ดูข้อมูลเกี่ยวกับวิธีให้สิทธิ์ในบริบทอื่นๆ ได้ที่ส่วน การให้สิทธิ์และการตรวจสอบสิทธิ์ ของ README ของไลบรารี

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