Drive API - Update/Create Google 来自字符串的文档 - Node.js

Drive API - Update/Create Google Doc from a string - Node.js

我正在使用 Drive API v3 (Node.js) 创建一个包含一些数据的 Google 文档。后来,我也想有在已有的Google Doc.

上“追加”新数据的可能

我编写了以下代码来在某个文件夹中创建一个新的 Google 文档:

          var content = "Content to be written in file"
          var fileMetadata = {
            name: filename,
            parents: [rootFolderId]
          };
          var media = {
            mimeType: 'application/vnd.google-apps.document',
            body: content  // In the form of string
          };
          drive.files.create({
            resource: fileMetadata,
            multipart: media,
            fields: 'id', 
          })
          .then(function (response) {
              // Handle the response
              console.log(response.data.name, "File created")
            },
            function (err) {
              console.error(err);
          })

我的问题是,如何创建 Doc,并用字符串对其进行初始化?我希望它在云端硬盘上可读。现在,正在创建一个二进制文件,其中 'No preview available'.

另外,我想要一个函数来更新这个文档(追加)一个字符串。像这样:

         var media = {
            mimeType: 'application/vnd.google-apps.document',
            body: content_to_be_appended // in the form of string
          };
         drive.files.update({
            fileId: existingDocID,
            resource: fileMetadata,
            multipart: media,
            fields: 'id, name'
          })

如有任何帮助,我们将不胜感激!谢谢!

我相信你的目标如下。

  • 您的问题包含以下2个问题。
    1. 您想知道创建包含文本数据的新Google文档的方法。
    2. 您想知道将更多文本数据添加到现有 Google 文档的方法。
  • 您想使用云端硬盘 API 和用于 Node.js 的 googleapis 来实现此目的。
  • 您已经能够使用驱动器 API 获取和放置文件。

问题 1 的答案:

在此答案中,新的 Google 文档是通过使用驱动器 API 包含文本数据创建的。

修改点:

  • 此时需要将文本转为流类型
  • 当文本转换为Google文档时,mimeType需要包含在fileMetadata中。

当以上几点反映到你的脚本中,就会变成下面这样。

修改后的脚本:

从:
var content = "Content to be written in file"
var fileMetadata = {
  name: filename,
  parents: [rootFolderId]
};
var media = {
  mimeType: 'application/vnd.google-apps.document',
  body: content  // In the form of string
};
到:
const stream = require("stream");

var filename = "sample filename";  // Please set the filename of created Google Document.
var rootFolderId = "root";  // Please set the folder ID.
var content = "Content to be written in file";

var bufferStream = new stream.PassThrough();
bufferStream.end(Uint8Array.from(Buffer.from(content, "binary")));
var fileMetadata = {
  name: filename,
  parents: [rootFolderId],
  mimeType: "application/vnd.google-apps.document",
};
var media = {
  mimeType: "text/plain",  // <--- Added
  body: bufferStream
};
  • 在这种情况下,使用 stream 模块。

问题 2 的答案:

在这个回答中,更多的文本数据被添加到现有的 Google 使用驱动器 API 的文档中。

修改点:

  • 在这种情况下,需要做如下流程。
    1. 从现有 Google 文档中检索所有文本数据。
    2. 为检索到的文本添加更多文本数据。
    3. 使用更新的文本数据更新现有的 Google 文档。
      • 在这种情况下,使用驱动器API中的“文件:更新”方法。

示例脚本如下

示例脚本:

const documentId = "###"; // Please set the Google Document ID of the existing Google Document.
drive.files.export(
  {
    fileId: documentId,
    mimeType: "text/plain",
  },
  { responseType: "stream" },
  (err, { data }) => {
    if (err) {
      console.log(err);
      return;
    }
    let buf = [];
    data.on("data", (e) => buf.push(e));
    data.on("end", () => {
      const stream = require("stream");

      const content = "\n" + "Added text data";  // Here, the text data is added to the existing text in Document.

      buf.push(Buffer.from(content, "binary"));
      const bufferStream = new stream.PassThrough();
      bufferStream.end(Uint8Array.from(Buffer.concat(buf)));
      var media = {
        body: bufferStream,
      };
      drive.files.update(
        {
          fileId: documentId,
          resource: {},
          media: media,
          fields: "id",
        },
        function (err, file) {
          if (err) {
            console.error(err);
            return;
          }
          console.log(file.data.id);
        }
      );
    });
  }
);
  • 在此示例脚本中,我使用 const content = "\n" + "Added text data"; 添加更多文本数据。如果您不想为此插入换行符,请删除 "\n".

注意:

  • 为了增加更多的文本数据,我想你也可以使用Docs API。但是在您的目标中,使用了 Drive API。所以我提出了Drive API.
  • 的使用方法

参考文献:

Media Uploads examplegoogleapis@60.0.1,您可以使用

在给定文件夹中创建具有给定标题和内容的 Google 文档
const drive = google.drive({ version: 'v3', auth });

const filename = '<filename>';
const parentFolderId = '<parent-folder-id>';
const content = '<file-content>';

const requestBody = {
  name: filename,
  parents: [parentFolderId],
  mimeType: 'application/vnd.google-apps.document',
};
const media = {
  mimeType: 'text/plain',
  body: content,
};

await drive.files.create({
  requestBody,
  media,
  fields: 'id',
});

要对文档进行修改,最好使用 Docs API。它提供了对文档修改的精细控制。

如果您正在寻找一种简单的解决方案来使用云端硬盘 API 更新 Google 文档的内容,则使用稍微粗略的方法文档 API 是

drive = google.drive({ version: 'v3', auth });

const fileId = '<file-id>';
const newContent = '<new content>';
const media = {
  mimeType: 'text/plain',
  body: newContent,
};

await drive.files.update({
  fileId,
  media,
});

使用驱动器API将文本附加到文档,您可以使用

const drive = google.drive({ version: 'v3', auth });

const fileId = '<file-id>';
const contentToAppend = '<new content>';

const { data: prevContent } = await drive.files.export({
  fileId,
  mimeType: 'text/plain',
});

const newContent = prevContent + contentToAppend;

const media = {
  mimeType: 'text/plain',
  body: newContent,
};

await drive.files.update({
  fileId,
  media,
});