constfs=require('fs').promises;constpath=require('path');constprocess=require('process');const{authenticate}=require('@google-cloud/local-auth');const{google}=require('googleapis');// If modifying these scopes, delete token.json.constSCOPES=['https://www.googleapis.com/auth/drive.metadata.readonly'];// The file token.json stores the user's access and refresh tokens, and is// created automatically when the authorization flow completes for the first// time.constTOKEN_PATH=path.join(process.cwd(),'token.json');constCREDENTIALS_PATH=path.join(process.cwd(),'credentials.json');/** * Reads previously authorized credentials from the save file. * * @return {Promise<OAuth2Client|null>} */asyncfunctionloadSavedCredentialsIfExist(){try{constcontent=awaitfs.readFile(TOKEN_PATH);constcredentials=JSON.parse(content);returngoogle.auth.fromJSON(credentials);}catch(err){returnnull;}}/** * Serializes credentials to a file compatible with GoogleAuth.fromJSON. * * @param {OAuth2Client} client * @return {Promise<void>} */asyncfunctionsaveCredentials(client){constcontent=awaitfs.readFile(CREDENTIALS_PATH);constkeys=JSON.parse(content);constkey=keys.installed||keys.web;constpayload=JSON.stringify({type:'authorized_user',client_id:key.client_id,client_secret:key.client_secret,refresh_token:client.credentials.refresh_token,});awaitfs.writeFile(TOKEN_PATH,payload);}/** * Load or request or authorization to call APIs. * */asyncfunctionauthorize(){letclient=awaitloadSavedCredentialsIfExist();if(client){returnclient;}client=awaitauthenticate({scopes:SCOPES,keyfilePath:CREDENTIALS_PATH,});if(client.credentials){awaitsaveCredentials(client);}returnclient;}/** * Lists the names and IDs of up to 10 files. * @param {OAuth2Client} authClient An authorized OAuth2 client. */asyncfunctionlistFiles(authClient){constdrive=google.drive({version:'v3',auth:authClient});constres=awaitdrive.files.list({pageSize:10,fields:'nextPageToken, files(id, name)',});constfiles=res.data.files;if(files.length===0){console.log('No files found.');return;}console.log('Files:');files.map((file)=>{console.log(`${file.name} (${file.id})`);});}authorize().then(listFiles).catch(console.error);
运行示例
在工作目录中,运行示例:
node .
首次运行该示例时,系统会提示您授予访问权限:
如果您尚未登录 Google 账号,请在系统提示时登录。如果您登录了多个账号,请选择一个账号用于授权。
[[["易于理解","easyToUnderstand","thumb-up"],["解决了我的问题","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["没有我需要的信息","missingTheInformationINeed","thumb-down"],["太复杂/步骤太多","tooComplicatedTooManySteps","thumb-down"],["内容需要更新","outOfDate","thumb-down"],["翻译问题","translationIssue","thumb-down"],["示例/代码问题","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["最后更新时间 (UTC):2025-02-24。"],[[["This quickstart demonstrates how to build a Node.js command-line application that interacts with the Google Drive API."],["You will need to set up your Google Cloud environment, install the necessary client libraries, and configure authentication."],["The provided code sample retrieves and lists the names and IDs of up to 10 files from your Google Drive."],["Before running the sample, ensure you have Node.js, npm, a Google Cloud project, and a Google account with Drive enabled."],["After authorization, the application calls the Google Drive API and stores authorization for subsequent runs."]]],["This document outlines how to set up and run a Node.js application that interacts with the Google Drive API. Key steps include enabling the Google Drive API, configuring the OAuth consent screen, and creating a desktop app client ID. You need to install the required libraries, create `credentials.json`, and implement an `index.js` file to authorize access and list files. The application uses the client library for simplified authentication, saving authorization information for future use, and the `node .` command runs the application.\n"]]