با مجموعهها، منظم بمانید
ذخیره و طبقهبندی محتوا براساس اولویتهای شما.
مراحل توضیح داده شده در ادامه این صفحه را کامل کنید و در عرض حدود پنج دقیقه یک برنامه ساده خط فرمان Node.js خواهید داشت که درخواست هایی را به YouTube Data API ارسال می کند.
کد نمونه استفاده شده در این راهنما، منبع channel را برای کانال YouTube GoogleDevelopers بازیابی می کند و برخی از اطلاعات اولیه را از آن منبع چاپ می کند.
پیش نیازها
برای اجرای این شروع سریع، به موارد زیر نیاز دارید:
Node.js نصب شده است.
ابزار مدیریت بسته npm (به همراه Node.js ارائه می شود).
دسترسی به اینترنت و مرورگر وب.
یک حساب کاربری گوگل
مرحله 1: YouTube Data API را روشن کنید
از این جادوگر برای ایجاد یا انتخاب یک پروژه در Google Developers Console استفاده کنید و به طور خودکار API را روشن کنید. روی Continue کلیک کنید، سپس به اعتبارنامه بروید .
در صفحه Create credentials ، روی دکمه Cancel کلیک کنید.
در بالای صفحه، برگه صفحه رضایت OAuth را انتخاب کنید. یک آدرس ایمیل را انتخاب کنید، نام محصول را در صورتی که قبلا تنظیم نشده است وارد کنید و روی دکمه ذخیره کلیک کنید.
تب Credentials را انتخاب کنید، روی دکمه Create credentials کلیک کنید و OAuth Client ID را انتخاب کنید.
نوع برنامه دیگر را انتخاب کنید، نام «YouTube Data API Quickstart» را وارد کنید و روی دکمه ایجاد کلیک کنید.
روی OK کلیک کنید تا گفتگوی بهدستآمده رد شود.
روی دکمه file_download (دانلود JSON) در سمت راست شناسه مشتری کلیک کنید.
فایل دانلود شده را به دایرکتوری کاری خود منتقل کنید و نام آن را client_secret.json تغییر دهید.
مرحله 2: کتابخانه مشتری را نصب کنید
برای نصب کتابخانه ها با استفاده از npm دستورات زیر را اجرا کنید:
یک فایل به نام quickstart.js در پوشه کاری خود ایجاد کنید و در کد زیر کپی کنید:
varfs=require('fs');varreadline=require('readline');var{google}=require('googleapis');varOAuth2=google.auth.OAuth2;// If modifying these scopes, delete your previously saved credentials// at ~/.credentials/youtube-nodejs-quickstart.jsonvarSCOPES=['https://www.googleapis.com/auth/youtube.readonly'];varTOKEN_DIR=(process.env.HOME||process.env.HOMEPATH||process.env.USERPROFILE)+'/.credentials/';varTOKEN_PATH=TOKEN_DIR+'youtube-nodejs-quickstart.json';// Load client secrets from a local file.fs.readFile('client_secret.json',functionprocessClientSecrets(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. */functionauthorize(credentials,callback){varclientSecret=credentials.installed.client_secret;varclientId=credentials.installed.client_id;varredirectUrl=credentials.installed.redirect_uris[0];varoauth2Client=newOAuth2(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. */functiongetNewToken(oauth2Client,callback){varauthUrl=oauth2Client.generateAuthUrl({access_type:'offline',scope:SCOPES});console.log('Authorize this app by visiting this url: ',authUrl);varrl=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. */functionstoreToken(token){try{fs.mkdirSync(TOKEN_DIR);}catch(err){if(err.code!='EEXIST'){throwerr;}}fs.writeFile(TOKEN_PATH,JSON.stringify(token),(err)=>{if(err)throwerr;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. */functiongetChannel(auth){varservice=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;}varchannels=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);}});}
اولین باری که نمونه را اجرا میکنید، از شما میخواهد که دسترسی را مجاز کنید:
URL ارائه شده در مرورگر وب خود را مرور کنید.
اگر قبلاً وارد حساب Google خود نشدهاید، از شما خواسته میشود که وارد شوید. اگر به چندین حساب Google وارد شدهاید، از شما خواسته میشود یک حساب را برای استفاده برای مجوز انتخاب کنید.
روی دکمه Accept کلیک کنید.
کدی که به شما داده شده را کپی کنید، آن را در خط فرمان قرار دهید و Enter را فشار دهید.
یادداشت ها
اطلاعات مجوز در سیستم فایل ذخیره می شود، بنابراین اجرای بعدی درخواست مجوز نمی کند.
جریان مجوز در این مثال برای یک برنامه خط فرمان طراحی شده است. برای اطلاعات در مورد نحوه اجرای مجوز در یک برنامه وب که از YouTube Data API استفاده می کند، به استفاده از OAuth 2.0 برای برنامه های وب سرور مراجعه کنید.
برای کسب اطلاعات در مورد نحوه اجرای مجوز در زمینه های دیگر، به بخش مجوز و احراز هویت در README کتابخانه مراجعه کنید.
تاریخ آخرین بهروزرسانی 2025-08-21 بهوقت ساعت هماهنگ جهانی.
[null,null,["تاریخ آخرین بهروزرسانی 2025-08-21 بهوقت ساعت هماهنگ جهانی."],[[["\u003cp\u003eThis guide walks you through creating a simple Node.js command-line application that interacts with the YouTube Data API to retrieve and display information from a YouTube channel in about five minutes.\u003c/p\u003e\n"],["\u003cp\u003eYou will need Node.js, npm, internet access, a web browser, and a Google account to complete the steps in this guide.\u003c/p\u003e\n"],["\u003cp\u003eThe setup involves enabling the YouTube Data API in the Google Developers Console, installing the necessary client libraries, setting up a \u003ccode\u003equickstart.js\u003c/code\u003e file with the provided code, and obtaining OAuth 2.0 credentials.\u003c/p\u003e\n"],["\u003cp\u003eRunning \u003ccode\u003enode quickstart.js\u003c/code\u003e will execute the sample code to retrieve and display basic information about the GoogleDevelopers YouTube channel.\u003c/p\u003e\n"],["\u003cp\u003eThe application stores authorization information on the file system, avoiding repeated authorization prompts on subsequent runs.\u003c/p\u003e\n"]]],["This guide outlines how to set up a Node.js command-line application to interact with the YouTube Data API. Key actions include: enabling the API via the Google Developers Console, creating OAuth credentials, and downloading the `client_secret.json` file. You will also need to install the `googleapis` and `google-auth-library` npm packages. Then, create a `quickstart.js` file with sample code, and run it. The first run requires browser authorization and code input, while subsequent runs will use stored authorization data. The code retrieves and displays channel data from the YouTube Data API.\n"],null,["# Node.js Quickstart\n\nComplete the steps described in the rest of this page, and in about five minutes\nyou'll have a simple Node.js command-line application that makes requests to the\nYouTube Data API.\nThe sample code used in this guide retrieves the `channel` resource for the GoogleDevelopers YouTube channel and prints some basic information from that resource.\n\nPrerequisites\n-------------\n\nTo run this quickstart, you'll need:\n\n- Node.js installed.\n- The [npm](https://www.npmjs.com/) package management tool (comes with Node.js).\n- Access to the internet and a web browser.\n- A Google account.\n\nStep 1: Turn on the YouTube Data API\n------------------------------------\n\n1. Use\n [this wizard](https://console.developers.google.com/start/api?id=youtube)\n to create or select a project in the Google Developers Console and\n automatically turn on the API. Click **Continue** , then\n **Go to credentials**.\n\n2. On the **Create credentials** page, click the\n **Cancel** button.\n\n3. At the top of the page, select the **OAuth consent screen** tab.\n Select an **Email address** , enter a **Product name** if not\n already set, and click the **Save** button.\n\n4. Select the **Credentials** tab, click the **Create credentials**\n button and select **OAuth client ID**.\n\n5. Select the application type **Other** , enter the name\n \"YouTube Data API Quickstart\", and click the **Create** button.\n\n6. Click **OK** to dismiss the resulting dialog.\n\n7. Click the file_download\n (Download JSON) button to the right of the client ID.\n\n8. Move the downloaded file to your working directory and rename it\n `client_secret.json`.\n\nStep 2: Install the client library\n----------------------------------\n\nRun the following commands to install the libraries using npm: \n\n npm install googleapis --save\n npm install google-auth-library --save\n\nStep 3: Set up the sample\n-------------------------\n\nCreate a file named `quickstart.js` in your working directory and copy in\nthe following code:\n\n\n```javascript\nvar fs = require('fs');\nvar readline = require('readline');\nvar {google} = require('googleapis');\nvar OAuth2 = google.auth.OAuth2;\n\n// If modifying these scopes, delete your previously saved credentials\n// at ~/.credentials/youtube-nodejs-quickstart.json\nvar SCOPES = ['https://www.googleapis.com/auth/youtube.readonly'];\nvar TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||\n process.env.USERPROFILE) + '/.credentials/';\nvar TOKEN_PATH = TOKEN_DIR + 'youtube-nodejs-quickstart.json';\n\n// Load client secrets from a local file.\nfs.readFile('client_secret.json', function processClientSecrets(err, content) {\n if (err) {\n console.log('Error loading client secret file: ' + err);\n return;\n }\n // Authorize a client with the loaded credentials, then call the YouTube API.\n authorize(JSON.parse(content), getChannel);\n});\n\n/**\n * Create an OAuth2 client with the given credentials, and then execute the\n * given callback function.\n *\n * @param {Object} credentials The authorization client credentials.\n * @param {function} callback The callback to call with the authorized client.\n */\nfunction authorize(credentials, callback) {\n var clientSecret = credentials.installed.client_secret;\n var clientId = credentials.installed.client_id;\n var redirectUrl = credentials.installed.redirect_uris[0];\n var oauth2Client = new OAuth2(clientId, clientSecret, redirectUrl);\n\n // Check if we have previously stored a token.\n fs.readFile(TOKEN_PATH, function(err, token) {\n if (err) {\n getNewToken(oauth2Client, callback);\n } else {\n oauth2Client.credentials = JSON.parse(token);\n callback(oauth2Client);\n }\n });\n}\n\n/**\n * Get and store new token after prompting for user authorization, and then\n * execute the given callback with the authorized OAuth2 client.\n *\n * @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.\n * @param {getEventsCallback} callback The callback to call with the authorized\n * client.\n */\nfunction getNewToken(oauth2Client, callback) {\n var authUrl = oauth2Client.generateAuthUrl({\n access_type: 'offline',\n scope: SCOPES\n });\n console.log('Authorize this app by visiting this url: ', authUrl);\n var rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout\n });\n rl.question('Enter the code from that page here: ', function(code) {\n rl.close();\n oauth2Client.getToken(code, function(err, token) {\n if (err) {\n console.log('Error while trying to retrieve access token', err);\n return;\n }\n oauth2Client.credentials = token;\n storeToken(token);\n callback(oauth2Client);\n });\n });\n}\n\n/**\n * Store token to disk be used in later program executions.\n *\n * @param {Object} token The token to store to disk.\n */\nfunction storeToken(token) {\n try {\n fs.mkdirSync(TOKEN_DIR);\n } catch (err) {\n if (err.code != 'EEXIST') {\n throw err;\n }\n }\n fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) =\u003e {\n if (err) throw err;\n console.log('Token stored to ' + TOKEN_PATH);\n });\n}\n\n/**\n * Lists the names and IDs of up to 10 files.\n *\n * @param {google.auth.OAuth2} auth An authorized OAuth2 client.\n */\nfunction getChannel(auth) {\n var service = google.youtube('v3');\n service.channels.list({\n auth: auth,\n part: 'snippet,contentDetails,statistics',\n forUsername: 'GoogleDevelopers'\n }, function(err, response) {\n if (err) {\n console.log('The API returned an error: ' + err);\n return;\n }\n var channels = response.data.items;\n if (channels.length == 0) {\n console.log('No channel found.');\n } else {\n console.log('This channel\\'s ID is %s. Its title is \\'%s\\', and ' +\n 'it has %s views.',\n channels[0].id,\n channels[0].snippet.title,\n channels[0].statistics.viewCount);\n }\n });\n}\nhttps://github.com/youtube/api-samples/blob/07263305b59a7c3275bc7e925f9ce6cabf774022/javascript/nodejs-quickstart.js\n```\n\n\u003cbr /\u003e\n\nStep 4: Run the sample\n----------------------\n\nRun the sample using the following command: \n\n node quickstart.js\n\nThe first time you run the sample, it will prompt you to authorize access:\n\n1. Browse to the provided URL in your web browser.\n\n If you are not already logged into your Google account, you will be\n prompted to log in. If you are logged into multiple Google accounts, you\n will be asked to select one account to use for the authorization.\n2. Click the **Accept** button.\n3. Copy the code you're given, paste it into the command-line prompt, and press **Enter**.\n\nIt worked! **Great!** Check out the further reading section below to learn more.\nI got an error **Bummer.** Thanks for letting us know and we'll work to fix this quickstart.\n\nNotes\n-----\n\n- Authorization information is stored on the file system, so subsequent executions will not prompt for authorization.\n- The authorization flow in this example is designed for a command line application. For information on how to perform authorization in a web application that uses the YouTube Data API, see [Using OAuth 2.0 for Web Server Applications](/youtube/v3/guides/auth/server-side-web-apps). \n\n For information on how to perform authorization in other contexts, see the [Authorizing and Authenticating](https://github.com/google/google-api-nodejs-client/#authorizing-and-authenticating) section of the library's README.\n\nFurther reading\n---------------\n\n- [Google Developers Console help documentation](/console/help/new)\n- [Google APIs Client for Node.js documentation](https://github.com/google/google-api-nodejs-client/#google-apis-nodejs-client)\n- [YouTube Data API reference documentation](/youtube/v3/docs)"]]