Javascript Google Drive API-如何提取Drive.file.list的结果?

Javascript Google Drive API-如何提取Drive.file.list的结果?,javascript,node.js,authentication,google-drive-api,Javascript,Node.js,Authentication,Google Drive Api,我正在尝试为客户建立一个搜索工具。我正在使用GoogleDrive API,以便从指定帐户提取不同文件及其元数据的列表,然后将这些文件添加到单独的本地数据库中,然后我可以在其中搜索。 当我在这段代码中使用console.log(fileArray)时,我得到了我想要的结果,问题是我无法让它离开函数的逻辑。目标是获取var fileArray,并将该数组映射到数据库中。我似乎无法从函数列表文件中提取或导出它。有什么想法吗?我只想在google drive数据填充变量后,将其移动到另一个文件中 谢谢

我正在尝试为客户建立一个搜索工具。我正在使用GoogleDrive API,以便从指定帐户提取不同文件及其元数据的列表,然后将这些文件添加到单独的本地数据库中,然后我可以在其中搜索。 当我在这段代码中使用console.log(fileArray)时,我得到了我想要的结果,问题是我无法让它离开函数的逻辑。目标是获取var fileArray,并将该数组映射到数据库中。我似乎无法从函数列表文件中提取或导出它。有什么想法吗?我只想在google drive数据填充变量后,将其移动到另一个文件中

谢谢大家!

const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');
const { file } = require('googleapis/build/src/apis/file');

// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/drive'];
// 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.
const TOKEN_PATH = 'token.json';

// Load client secrets from a local file.
const authenticate = fs.readFile('credentials.json', (err, content) => {
  if (err) return console.log('Error loading client secret file:', err);
  // Authorize a client with credentials, then call the Google Drive API.
  authorize(JSON.parse(content), listFiles);
});

/**
 * 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) {
  const {client_secret, client_id, redirect_uris} = credentials.installed;
  const oAuth2Client = new google.auth.OAuth2(
      client_id, client_secret, redirect_uris[0]);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return getAccessToken(oAuth2Client, callback);
    oAuth2Client.setCredentials(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 for the authorized client.
 */
function getAccessToken(oAuth2Client, callback) {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES,
  });
  console.log('Authorize this app by visiting this url:', authUrl);
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  rl.question('Enter the code from that page here: ', (code) => {
    rl.close();
    oAuth2Client.getToken(code, (err, token) => {
      if (err) return console.error('Error retrieving access token', err);
      oAuth2Client.setCredentials(token);
      // Store the token to disk for later program executions
      fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
        if (err) return console.error(err);
        console.log('Token stored to', TOKEN_PATH);
      });
      callback(oAuth2Client);
    });
  });
}

/**
 * Lists the names and IDs of up to 10 files.
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
function listFiles(auth) {
  const drive = google.drive({version: 'v3', auth});
  const fileArray = [];
   drive.files.list({
    pageSize: 100,
    fields: 'nextPageToken, files(id, name, mimeType, createdTime, parents, properties)',
  }, (err, res) => {
    if (err) return console.log('The API returned an error: ' + err);
    const files = res.data.files;
    if (files.length) {
      const fileDisplay = []; 
      const fileId = [];
      const mimeType = []; 
      const parents = [];
      const properties = [];
      console.log('Files:');
      for (var i = 0; i < files.length; i++) {
        fileDisplay.push(files[i].name);
        fileId.push(files[i].id);
        mimeType.push(files[i].mimeType);
        properties.push(files[i].properties);
        parents.push(files[i].parents);
      }
      for(var y = 0; y < fileDisplay.length; y++) {
        fileArray.push({file: fileDisplay[y], id: fileId[y], type: mimeType[y], parents: parents[y], properties: properties[y]});
      }
    } else {
      console.log('No files found.');
    }
  });
}
const fs=require('fs');
const readline=require('readline');
const{google}=require('googleapis');
const{file}=require('googleapis/build/src/api/file');
//如果修改这些作用域,请删除token.json。
常量作用域=['https://www.googleapis.com/auth/drive'];
//文件token.json存储用户的访问和刷新令牌,并且
//在第一次完成授权流时自动创建
//时间。
const TOKEN_PATH='TOKEN.json';
//从本地文件加载客户端机密。
const authenticate=fs.readFile('credentials.json',(err,content)=>{
if(err)返回console.log('加载客户端机密文件时出错:',err);
//使用凭据授权客户端,然后调用Google Drive API。
授权(JSON.parse(content),listFiles);
});
/**
*使用给定的凭据创建OAuth2客户端,然后执行
*给定回调函数。
*@param{Object}凭据授权客户端凭据。
*@param{function}回调使用授权客户端调用的回调。
*/
函数授权(凭据、回调){
const{client\u secret,client\u id,redirect\u uris}=credentials.installed;
const oAuth2Client=new google.auth.OAuth2(
客户端id、客户端机密、重定向URI[0]);
//检查我们以前是否存储过令牌。
fs.readFile(令牌路径,(错误,令牌)=>{
if(err)返回getAccessToken(oAuth2Client,回调);
oAuth2Client.setCredentials(JSON.parse(token));
回调(oAuth2Client);
});
}
/**
*提示用户授权后获取并存储新令牌,然后
*使用授权的OAuth2客户端执行给定的回调。
*@param{google.auth.OAuth2}OAuth2客户端为OAuth2客户端获取令牌。
*@param{getEventsCallback}回调授权客户端的回调。
*/
函数getAccessToken(oAuth2Client,回调){
const authUrl=oAuth2Client.generateAuthUrl({
访问类型:“脱机”,
范围:范围,
});
log('通过访问此url授权此应用:',authUrl);
const rl=readline.createInterface({
输入:process.stdin,
输出:process.stdout,
});
rl.question('在此处输入该页面的代码:',(代码)=>{
rl.close();
oAuth2Client.getToken(代码,(错误,标记)=>{
if(err)返回console.error('检索访问令牌时出错',err);
oAuth2Client.setCredentials(令牌);
//将令牌存储到磁盘,以便以后执行程序
fs.writeFile(TOKEN_PATH,JSON.stringify(TOKEN),(err)=>{
if(err)返回控制台。error(err);
日志('令牌存储到',令牌路径);
});
回调(oAuth2Client);
});
});
}
/**
*列出最多10个文件的名称和ID。
*@param{google.auth.OAuth2}对授权的OAuth2客户端进行身份验证。
*/
函数列表文件(auth){
const drive=google.drive({version:'v3',auth});
常量文件数组=[];
drive.files.list({
页面大小:100,
字段:“nextPageToken、文件(id、名称、mimeType、createdTime、父项、属性)”,
},(误差、分辨率)=>{
if(err)返回console.log('API返回错误:'+err);
const files=res.data.files;
if(files.length){
constfiledisplay=[];
常量fileId=[];
常量mimeType=[];
const parents=[];
常量属性=[];
log('Files:');
对于(var i=0;i
在Node.js的googleapis中,
drive.files.list
返回承诺。那么使用这个,这个修改怎么样

修改脚本: 参考:

谢谢您的回答!我正在看我现在是否可以使用这个代码。“我甚至没有想过要分开开车的电话。”马特.G谢谢你的回复。如果我的建议不是你期望的方向,我很抱歉。它实际上帮助了很多!这让我想到了解决这个问题的不同方法谢谢大家!@Tanaike@Matt.G欢迎谢谢你让我知道。我很高兴你的问题解决了。如果您的问题已解决,请按“接受”按钮。与您有相同问题的其他人也可以将您的问题作为可以解决的问题。我认为你的问题和解决方案对他们会有帮助。如果你找不到按钮,尽管告诉我@Matt.G我能为你的问题做点什么吗?如果我的回答对你的处境没有帮助。我必须道歉并修改它。如果你能合作解决你的问题,我很高兴。我想考虑一下解决办法。
async function getFileList(drive) {
  const res = await drive.files.list({
    pageSize: 10,
    fields: "nextPageToken, files(id, name, mimeType, createdTime, parents, properties)",
  });
  const files = res.data.files;
  const fileArray = [];
  if (files.length) {
    const fileDisplay = [];
    const fileId = [];
    const mimeType = [];
    const parents = [];
    const properties = [];
    console.log("Files:");
    for (var i = 0; i < files.length; i++) {
      fileDisplay.push(files[i].name);
      fileId.push(files[i].id);
      mimeType.push(files[i].mimeType);
      properties.push(files[i].properties);
      parents.push(files[i].parents);
    }
    for (var y = 0; y < fileDisplay.length; y++) {
      fileArray.push({
        file: fileDisplay[y],
        id: fileId[y],
        type: mimeType[y],
        parents: parents[y],
        properties: properties[y],
      });
    }
  }
  return fileArray;
}

async function listFiles(auth) {
  const drive = google.drive({ version: "v3", auth });
  const fileArray = await getFileList(drive).catch((err) => {
    if (err) console.log(err);
  });
  console.log(fileArray);
}
function listFiles(auth) {
  const drive = google.drive({ version: "v3", auth });
  getFileList(drive)
    .then((fileArray) => console.log(fileArray))
    .catch((err) => {
      if (err) console.log(err);
    });
}