首页 > 解决方案 > Drive API - 从字符串更新/创建 Google Doc - Node.js

问题描述

我正在使用 Drive API v3 (Node.js) 来创建包含一些数据的 Google Doc。后来,我还希望有可能将新数据“附加”到现有的 Google Doc 中。

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

          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,并用字符串对其进行初始化?我希望它在云端硬盘上可读。现在,正在创建一个二进制文件,其中“没有可用的预览”。

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

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

任何帮助将不胜感激!谢谢!

标签: node.jsgoogle-drive-apigoogle-docsgoogle-docs-api

解决方案


我相信你的目标如下。

  • 您的问题有以下 2 个问题。
    1. 您想知道创建包含文本数据的新 Google 文档的方法。
    2. 您想知道将更多文本数据添加到现有 Google 文档的方法。
  • 您想使用 Drive API 和 googleapis for Node.js 来实现这一点。
  • 您已经能够使用 Drive API 获取和放置文件。

问题 1 的答案:

在此答案中,通过使用 Drive 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 的答案:

在这个答案中,使用 Drive API 将更多文本数据添加到现有的 Google 文档中。

修改点:

  • 在这种情况下,需要进行以下流程。
    1. 从现有的 Google 文档中检索所有文本数据。
    2. 将更多文本数据添加到检索到的文本中。
    3. 使用更新的文本数据更新现有的 Google 文档。
      • 在这种情况下,使用 Drive 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的方法。

参考:


推荐阅读