将文件正确写入Google云端硬盘,但云端硬盘文件夹中没有文件

时间:2019-10-14 12:02:46

标签: google-cloud-platform google-drive-api google-cloud-functions google-cloud-storage

我正在尝试使用Google Drive API将文件从Google Cloud Storage传输到Google Drive。在云端功能上运行此代码后,没有引发任何错误,但是在驱动器文件夹中没有看到任何文件。我的驱动器文件夹被设置为可公开访问以进行测试。有人知道这个问题或有任何疑难解答的提示吗?

我的源代码如下:


const Storage = require('@google-cloud/storage');
const fs = require('fs');
const {google} = require('googleapis');
const apiKey = 'xxxxxxxx';
const storage = Storage();

exports.GCS2Drive = (event, context) => {
  const auth = apiKey;
  const downloadLink = event.mediaLink;
  const fileName = event.name;
  console.log(downloadLink);
  console.log(fileName);
  const filePath = downloadLink.toString();

  const drive = google.drive({version: 'v3', auth});
  var folderId ='XXXXXXXXX';
  var fileMetadata = {
    'name': fileName,
    parents: [folderId]
  };

  var media = {
    mimeType: 'text/csv',
    body: fs.createReadStream(filePath)
  };

  drive.files.create({
    resource: fileMetadata,
    media: media,
    fields: 'id'
  },function (err, file) {
  if (err) {
    // Handle error
    console.error(err);
  } else {
    console.log(file.id);}
  }
  )

  console.log(`complete`);
};

1 个答案:

答案 0 :(得分:0)

您应该做的是在承诺中包含the drive.files.create()方法。

Promise对象表示一个值,该值可能尚不可用,但将来会被解析。它允许您以更同步的方式编写异步代码。

下面我将提供一些文章,详细解释如何使用Promise。

How to write Promises in JavaScript

JavaScript Promises

让我知道这是否有帮助。