Node.js googleapi节点模块中的google.youtube不是一个函数吗?

Node.js googleapi节点模块中的google.youtube不是一个函数吗?,node.js,google-api,youtube-api,youtube-data-api,Node.js,Google Api,Youtube Api,Youtube Data Api,各位晚上好, 我试图请求节点js中的Youtube API从字符串url获取视频JSON。 我阅读了youtube api,它几乎引导我编写以下代码。这不起作用,因为google.youtube不是一个函数。 主要问题似乎来自videosListById函数。google.youtube应该从googleapi节点模块导入,如api指南所示 var fs = require("fs"); var readline = require("readline"); var google = requi

各位晚上好, 我试图请求节点js中的Youtube API从字符串url获取视频JSON。 我阅读了youtube api,它几乎引导我编写以下代码。这不起作用,因为google.youtube不是一个函数。 主要问题似乎来自videosListById函数。google.youtube应该从googleapi节点模块导入,如api指南所示

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/google-apis-nodejs-quickstart.json
var SCOPES = ["https://www.googleapis.com/auth/youtube.force-ssl"];
var TOKEN_DIR = "src/google/.credentials/";
var TOKEN_PATH = TOKEN_DIR + "google-api-tokens.json";

getYoutubeVideo("https://www.youtube.com/watch?v=_zJ1b-atqpA");

function getYoutubeVideoId(url) {
  return url.split("=")[1];
}

// Load client secrets from a local file.
function getYoutubeVideo(url) {
  const _id = getYoutubeVideoId(url);
  fs.readFile("src/google/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.
    //See full code sample for authorize() function code.
    authorize(
      JSON.parse(content),
      {
        params: { id: _id, part: "snippet,contentDetails,statistics" }
      },
      videosListById
    );
  });
}

/**
 * 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, requestData, callback) {
  var clientSecret = credentials.installed.client_secret;
  var clientId = credentials.installed.client_id;
  var redirectUrl = credentials.installed.redirect_uris[0];
  var oauth2Client = new googleAuth.OAuth2Client(
    clientId,
    clientSecret,
    redirectUrl
  );

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

/**
 * 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, requestData, 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, requestData);
    });
  });
}

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

/**
 * Remove parameters that do not have values.
 *
 * @param {Object} params A list of key-value pairs representing request
 *                        parameters and their values.
 * @return {Object} The params object minus parameters with no values set.
 */
function removeEmptyParameters(params) {
  for (var p in params) {
    if (!params[p] || params[p] == "undefined") {
      delete params[p];
    }
  }
  return params;
}

/**
 * Create a JSON object, representing an API resource, from a list of
 * properties and their values.
 *
 * @param {Object} properties A list of key-value pairs representing resource
 *                            properties and their values.
 * @return {Object} A JSON object. The function nests properties based on
 *                  periods (.) in property names.
 */
function createResource(properties) {
  var resource = {};
  var normalizedProps = properties;
  for (var p in properties) {
    var value = properties[p];
    if (p && p.substr(-2, 2) == "[]") {
      var adjustedName = p.replace("[]", "");
      if (value) {
        normalizedProps[adjustedName] = value.split(",");
      }
      delete normalizedProps[p];
    }
  }
  for (var p in normalizedProps) {
    // Leave properties that don't have values out of inserted resource.
    if (normalizedProps.hasOwnProperty(p) && normalizedProps[p]) {
      var propArray = p.split(".");
      var ref = resource;
      for (var pa = 0; pa < propArray.length; pa++) {
        var key = propArray[pa];
        if (pa == propArray.length - 1) {
          ref[key] = normalizedProps[p];
        } else {
          ref = ref[key] = ref[key] || {};
        }
      }
    }
  }
  return resource;
}

function videosListById(auth, requestData) {
  /*var service = google.youtube({
    version: "v3",
    auth: process.env.API_KEY
  });*/
  var service = google.youtube("v3");
  var parameters = removeEmptyParameters(requestData["params"]);
  parameters["auth"] = auth;
  service.videos.list(parameters, function(err, response) {
    if (err) {
      console.log("The API returned an error: " + err);
      return;
    }
    console.log(response);
  });
}
var fs=require(“fs”);
var readline=需要(“readline”);
var google=require(“googleapis”);
var googleAuth=require(“谷歌认证库”);
//如果修改这些作用域,请删除以前保存的凭据
//位于~/.credentials/google-api-nodejs-quickstart.json
变量作用域=[”https://www.googleapis.com/auth/youtube.force-ssl"];
var TOKEN_DIR=“src/google/.credentials/”;
var TOKEN_PATH=TOKEN_DIR+“google api tokens.json”;
getYoutubeVideo(“https://www.youtube.com/watch?v=_zJ1b-atqpA”);
函数getYoutubeVideoId(url){
返回url.split(“=”[1];
}
//从本地文件加载客户端机密。
函数getYoutubeVideo(url){
const_id=getYoutubeVideoId(url);
fs.readFile(“src/google/client_secret.json”,函数processClientSecrets(
犯错误
内容
) {
如果(错误){
log(“加载客户端机密文件时出错:“+err”);
返回;
}
//使用加载的凭据授权客户端,然后调用YouTube API。
//有关authorize()函数代码,请参阅完整代码示例。
授权(
JSON.parse(内容),
{
参数:{id:_id,部分:“代码段,内容详细信息,统计信息”}
},
录像带字节
);
});
}
/**
*使用给定的凭据创建OAuth2客户端,然后执行
*给定回调函数。
*
*@param{Object}凭据授权客户端凭据。
*@param{function}回调使用授权客户端调用的回调。
*/
函数授权(凭据、请求数据、回调){
var clientSecret=credentials.installed.client\u secret;
var clientId=credentials.installed.client\u id;
var redirectUrl=credentials.installed.redirect_uris[0];
var oauth2Client=新的googleAuth.oauth2Client(
clientId,
客户机密,
重定向URL
);
//检查我们以前是否存储过令牌。
fs.readFile(令牌\路径,函数(err,令牌){
如果(错误){
getNewToken(oauth2Client、requestData、回调);
}否则{
oauth2Client.credentials=JSON.parse(令牌);
回调(oauth2Client、requestData);
}
});
}
/**
*提示用户授权后获取并存储新令牌,然后
*使用授权的OAuth2客户端执行给定的回调。
*
*@param{google.auth.OAuth2}OAuth2客户端为OAuth2客户端获取令牌。
*@param{getEventsCallback}回调使用授权的
*客户。
*/
函数getNewToken(oauth2Client、requestData、回调){
var authUrl=oauth2Client.generateAuthUrl({
访问类型:“脱机”,
范围:范围
});
log(“通过访问此url授权此应用:”,authUrl);
var rl=readline.createInterface({
输入:process.stdin,
输出:process.stdout
});
rl.问题(“在此处输入该页面的代码:”,函数(代码){
rl.close();
oauth2Client.getToken(代码、函数(错误、令牌){
如果(错误){
log(“尝试检索访问令牌时出错”,err);
返回;
}
oauth2Client.credentials=令牌;
storeToken(token);
回调(oauth2Client、requestData);
});
});
}
/**
*将令牌存储到磁盘,以便在以后的程序执行中使用。
*
*@param{Object}标记要存储到磁盘的标记。
*/
函数storeToken(token){
试一试{
fs.mkdirSync(TOKEN_DIR);
}捕捉(错误){
if(err.code!=“EEXIST”){
犯错误;
}
}
writeFile(TOKEN_PATH,JSON.stringify(TOKEN));
console.log(“存储到“+令牌_路径的令牌”);
}
/**
*删除没有值的参数。
*
*@param{Object}params表示请求的键值对列表
*参数及其值。
*@return{Object}参数对象减去未设置值的参数。
*/
函数removeEmptyParameters(参数){
for(参数中的var p){
如果(!params[p]| | params[p]=“未定义”){
删除参数[p];
}
}
返回参数;
}
/**
*从列表中创建一个JSON对象,表示API资源
*属性及其值。
*
*@param{Object}properties表示资源的键值对列表
*属性及其值。
*@return{Object}一个JSON对象。函数嵌套基于的属性
*属性名称中的句点(.)。
*/
函数createResource(属性){
var资源={};
var normalizedProps=属性;
对于(属性中的var p){
var值=属性[p];
如果(p&p.substr(-2,2)=“[]”){
var adjustedName=p.replace(“[]”,“”);
如果(值){
normalizedProps[adjustedName]=value.split(“,”);
}
删除规范化道具[p];
}
}
for(normalizedProps中的var p){
//将没有值的属性保留在插入的资源之外。
if(normalizedProps.hasOwnProperty(p)和&normalizedProps[p]){
var propArray=p.split(“.”);
var ref=资源;
对于(var pa=0;pavar google = require("googleapis");
var {google} = require("googleapis");