最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

如何使用循环来上传多个文件到谷歌云端硬盘API(的forEach)

IT培训 admin 5浏览 0评论

如何使用/循环来上传多个文件到谷歌云端硬盘API(的forEach)

我使用谷歌云端硬盘API来上传多个文件。我面临着耗尽RAM的问题,同时上载倍数的文件。我尝试使用的forEach(for循环)为我的代码,以避免同时上传多个文件,但它不工作,我所期望的方式。它总是通过列表文件的整个循环并上传同一时间。

我尝试使用异步/ AWAIT语法来阻止循环,但它没有工作,我所期望的方式。这里是我的代码:

const fs = require("fs");
const readline = require("readline");
const { google } = require("googleapis");

let files = ["file1.mp4", "file2.mp4"];

const SCOPES = [".metadata.readonly"];

const TOKEN_PATH = "token.json";
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), uploadFiles);
});

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

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) console.error(err);
        console.log("Token stored to", TOKEN_PATH);
      });
      callback(oAuth2Client);
    });
  });
}

async function uploadFiles(auth) {
  for (file of files) {
    var fileMetadata = {
      name: file
    };
    var media = {
      body: fs.createReadStream("test/" + file)
    };
    google.drive({ version: "v3", auth });
    const result = await drive.files.create(
      {
        resource: fileMetadata,
        media: media,
        fields: "id"
      },
      function(err, fileid) {
        if (err) {
          // Handle error
          console.error(err);
        } else {
          console.log("File Id: ", fileid.data.id);
          console.log("Uploaded..:" + file);
        }
      }
    );
    console.log("Uploading file..:" + file);
  }
}
回答如下:

我尝试使用的forEach(for循环)为我的代码,以避免同时上传多个文件

你不能,这个过程是完全异步的。您传递一个回调作为参数传递给函数drive.files.create

顺便说一句,如果你想使用async/await,你应该换你的函数成promisified之一。

function myCreateFunc (fileInfos) {
    return new Promise((resolve, reject) => {
            google.drive.create(filesInfos, function callback(err, fileId) {
                    if(err)
                        reject(err)

                    resolve(fileId)
            })
    });
}

如何使用/循环来上传多个文件到谷歌云端硬盘API(的forEach)

我使用谷歌云端硬盘API来上传多个文件。我面临着耗尽RAM的问题,同时上载倍数的文件。我尝试使用的forEach(for循环)为我的代码,以避免同时上传多个文件,但它不工作,我所期望的方式。它总是通过列表文件的整个循环并上传同一时间。

我尝试使用异步/ AWAIT语法来阻止循环,但它没有工作,我所期望的方式。这里是我的代码:

const fs = require("fs");
const readline = require("readline");
const { google } = require("googleapis");

let files = ["file1.mp4", "file2.mp4"];

const SCOPES = [".metadata.readonly"];

const TOKEN_PATH = "token.json";
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), uploadFiles);
});

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

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) console.error(err);
        console.log("Token stored to", TOKEN_PATH);
      });
      callback(oAuth2Client);
    });
  });
}

async function uploadFiles(auth) {
  for (file of files) {
    var fileMetadata = {
      name: file
    };
    var media = {
      body: fs.createReadStream("test/" + file)
    };
    google.drive({ version: "v3", auth });
    const result = await drive.files.create(
      {
        resource: fileMetadata,
        media: media,
        fields: "id"
      },
      function(err, fileid) {
        if (err) {
          // Handle error
          console.error(err);
        } else {
          console.log("File Id: ", fileid.data.id);
          console.log("Uploaded..:" + file);
        }
      }
    );
    console.log("Uploading file..:" + file);
  }
}
回答如下:

我尝试使用的forEach(for循环)为我的代码,以避免同时上传多个文件

你不能,这个过程是完全异步的。您传递一个回调作为参数传递给函数drive.files.create

顺便说一句,如果你想使用async/await,你应该换你的函数成promisified之一。

function myCreateFunc (fileInfos) {
    return new Promise((resolve, reject) => {
            google.drive.create(filesInfos, function callback(err, fileId) {
                    if(err)
                        reject(err)

                    resolve(fileId)
            })
    });
}
发布评论

评论列表 (0)

  1. 暂无评论