如何在google auth环境中返回js函数数据以供其他函数使用

问题描述 投票:0回答:1

我的测试脚本是:

// Test file that aquires authorization to list file ids/names from My Drive > ocrTarget

const fs = require('fs');
const fsp = fs.promises;


const path = require('path');
const process = require('process');
const {authenticate} = require('@google-cloud/local-auth');
const {google} = require('googleapis');

// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/drive'];
// File id of the file to download
const FILEID = '11Sejh6XG-2WzycpcC-MaEmDQJc78LCFg';


// 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 = path.join(process.cwd(), 'DownloadFileToken.json');
const CREDENTIALS_PATH = 'C:\\googleDriveDev\\credentials.json';

/**
 * Reads previously authorized credentials from the save file.
 *
 * @return {Promise<OAuth2Client|null>}
 */
async function loadSavedCredentialsIfExist() {
    try {
        const content = await fsp.readFile(TOKEN_PATH);
        const credentials = JSON.parse(content);
        return google.auth.fromJSON(credentials);
    } catch (err) {
        return null;
    }
}

/**
 * Serializes credentials to a file compatible with GoogleAUth.fromJSON.
 *
 * @param {OAuth2Client} client
 * @return {Promise<void>}
 */
async function saveCredentials(client) {
    const content = await fsp.readFile(CREDENTIALS_PATH);
    const keys = JSON.parse(content);
    const key = keys.installed || keys.web;
    const payload = JSON.stringify({
        type: 'authorized_user',
        client_id: key.client_id,
        client_secret: key.client_secret,
        refresh_token: client.credentials.refresh_token,
    });
    await fsp.writeFile(TOKEN_PATH, payload);
}

/**
 * Load or request or authorization to call APIs.
 *
 */
async function authorize() {
    let client = await loadSavedCredentialsIfExist();
    if (client) {
        return client;
    }
    client = await authenticate({
        scopes: SCOPES,
        keyfilePath: CREDENTIALS_PATH,
    });
    if (client.credentials) {
        await saveCredentials(client);
    }
    return client;
}


/**
 * Lists the names and IDs of pageSize number of files (using query to define folder of files)
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
function listFiles(auth) {
  const drive = google.drive({version: 'v3', auth});
 
 
  drive.files.list({
    corpora: 'user',  
    pageSize: 100,
    // files in a parent folder that have not been trashed 
    // get ID from Drive > Folder by looking at the URL after /folders/ 
    q: `'11Sejh6XG-2WzycpcC-MaEmDQJc78LCFg' in parents and trashed=false`,    
    fields: 'nextPageToken, files(id, name)',
  }, (err, res) => {
    if (err) return console.log('The API returned an error: ' + err);
    const files = res.data.files;
    if (files.length) {
     
        var idFiles = [ ];
        files.forEach(function(file, i) {
        idFiles.push(file.id);
        idFiles.push(file.name);
        });

        // Store file id/name pairs for use later
        var fileIdentity = [];

        // Iterate over idFiles array with step of 2
        for (var i = 0; i < idFiles.length; i += 2) {
            // Push pair of values into d array
            fileIdentity.push([idFiles[i], idFiles[i + 1]]);
        }
        
        // Access pairs using indices in order to pass an array pair of file id/file name into a function
        for (var i = 0; i < fileIdentity.length; i++) {
            console.log("File id:", fileIdentity[i][0], "has file name:", fileIdentity[i][1])       
        }

    } 
    else 
        {
        console.log('No files found.');
        }

        
  });

}

authorize().then(listFiles).catch(console.error);

输出:

C:\googleDriveDev>node ./exportTest3.js
File id: 15lsfdIP1Jne-x-rPI57BtWQE3W4ciZzDz9Wy4uU9J98 has file name: 31832_226133__0002-00104
File id: 1RK_172AaDBLji941voUn1TeAg6u6We-UQ8G280e2xsg has file name: 31832_226133__0002-00105
File id: 13B0Kt6PhQYalqh046eXJxnbT9ZCLZDhv2XZqF5SHdV4 has file name: 31832_226133__0002-00106
File id: 1Aj_jQ3nSZAMPlap7fC6lk2uEN7ajIuUL5Kx-JusE1O4 has file name: 31832_226133__0002-00107
File id: 1rTnen5Zhb-aV9k82cNqbbVVl8f54QDGRAdT6o7Ob2b8 has file name: 31832_226133__0002-00108

------------------><---------------

我不想在函数中输出 id/names 数组对

listFiles()
我想返回数组
fileIdentity
并在函数外迭代它。

我没有太多 JavaScript 经验。我发现练习中简单的函数返回还可以。但这个例子有额外的复杂性。放置

return fileIdentity
一直没问题(没有错误)但是当我尝试输出返回的内容时,我的数组 var 被确定为
undefined
并尝试另一个组合,我得到:

The API returned an error: Error: The request is missing a valid API key.

将此数据放在函数之外有助于将其传递到流程中的下一个函数。

javascript google-drive-api
1个回答
0
投票

虽然我不确定是否能正确理解你的预期结果,但是下面的修改怎么样?

来自:

function listFiles(auth) {
  const drive = google.drive({version: 'v3', auth});
 
 
  drive.files.list({
    corpora: 'user',  
    pageSize: 100,
    // files in a parent folder that have not been trashed 
    // get ID from Drive > Folder by looking at the URL after /folders/ 
    q: `'11Sejh6XG-2WzycpcC-MaEmDQJc78LCFg' in parents and trashed=false`,    
    fields: 'nextPageToken, files(id, name)',
  }, (err, res) => {
    if (err) return console.log('The API returned an error: ' + err);
    const files = res.data.files;
    if (files.length) {
     
        var idFiles = [ ];
        files.forEach(function(file, i) {
        idFiles.push(file.id);
        idFiles.push(file.name);
        });

        // Store file id/name pairs for use later
        var fileIdentity = [];

        // Iterate over idFiles array with step of 2
        for (var i = 0; i < idFiles.length; i += 2) {
            // Push pair of values into d array
            fileIdentity.push([idFiles[i], idFiles[i + 1]]);
        }
        
        // Access pairs using indices in order to pass an array pair of file id/file name into a function
        for (var i = 0; i < fileIdentity.length; i++) {
            console.log("File id:", fileIdentity[i][0], "has file name:", fileIdentity[i][1])       
        }

    } 
    else 
        {
        console.log('No files found.');
        }

        
  });

}

authorize().then(listFiles).catch(console.error);

致:

function listFiles(auth) {
  const drive = google.drive({ version: "v3", auth });
  return new Promise((resolve, reject) => {
    drive.files.list(
      {
        corpora: "user",
        pageSize: 100,
        // files in a parent folder that have not been trashed
        // get ID from Drive > Folder by looking at the URL after /folders/
        q: `'11Sejh6XG-2WzycpcC-MaEmDQJc78LCFg' in parents and trashed=false`, 
        fields: "nextPageToken, files(id, name)",
      },
      (err, res) => {
        // console.log(err);
        if (err) {
          reject("The API returned an error: " + err);
          return;
        }
        const files = res.data.files;
        if (files.length) {
          var idFiles = [];
          files.forEach(function (file, i) {
            idFiles.push(file.id);
            idFiles.push(file.name);
          });

          // Store file id/name pairs for use later
          var fileIdentity = [];

          // Iterate over idFiles array with step of 2
          for (var i = 0; i < idFiles.length; i += 2) {
            // Push pair of values into d array
            fileIdentity.push([idFiles[i], idFiles[i + 1]]);
          }
          resolve({ fileIdentity, msg: "" });
        } else {
          resolve({ fileIdentity: [], msg: "No files found." });
        }
      }
    );
  });
}

authorize()
  .then(listFiles)
  .then(({ fileIdentity, msg }) => {
    if (fileIdentity.length > 0) {
      for (var i = 0; i < fileIdentity.length; i++) {
        console.log("File id:", fileIdentity[i][0], "has file name:", fileIdentity[i][1]);
      }
    } else {
      console.log(msg);
    }
  })
  .catch(console.error);
  • 在这次修改中,我只是修改了您的显示脚本。
  • fileIdentity
    有值时,该值会以
    console.log("File id:", fileIdentity[i][0], "has file name:", fileIdentity[i][1])
    显示。当
    fileIdentity
    没有值时,
    No files found.
    显示为
    console.log(msg)
  • 当发生与 API 请求相关的错误时,该错误会显示为
    catch(console.error)
© www.soinside.com 2019 - 2024. All rights reserved.