gpt4 book ai didi

node.js - 使用 Node 创建带有内置对象的 Google 文档

转载 作者:太空宇宙 更新时间:2023-11-03 23:51:15 27 4
gpt4 key购买 nike

我看过下面关于如何使用 Node.js 创建 Google 文档实例的帖子。

Create a Google Document with Google Drive API and Node.js

但我也想传递一个对象,这样当创建谷歌文档时,它就会将该对象存储在其环境中。有没有办法通过以下参数之一传递对象来实现此目的?

DRIVE.files.create({
resource: {
name: fileName,
mimeType: fileType
},
media: {
mimeType: fileType,
body: fileContent
}
}

任何帮助将不胜感激

最佳答案

  • 您希望通过将 Google Apps 脚本包含为容器绑定(bind)脚本来创建新的 Google 文档。
    • 作为示例情况,您希望包含 var obj = { “foo”:”bar”} 脚本。
  • 您希望使用 googleapis 和 Node.js 来实现此目的。

如果我的理解是正确的,这个答案怎么样?请将此视为几个可能答案之一。

在本答案中,为了实现此目的,我使用了 Google Apps Script API 中的projects.create 和projects.updateContent 方法。

流程:

这个答案的流程如下。

  1. 创建新的 Google 文档。
  2. 创建新的 GAS 项目作为已创建的 Google 文档的容器绑定(bind)脚本。
  3. 将脚本放入已创建的GAS项目中。

准备工作:

在运行脚本之前,请做好以下准备。

  1. 请在 API 控制台启用 Google Apps 脚本 API。
    • 从您的问题来看,我认为您已经在 API 控制台启用了 Drive API。
  2. 请设置 https://www.googleapis.com/auth/drivehttps://www.googleapis.com/auth/script.projects 的范围>.
  3. 请删除包含访问 token 和刷新 token 的凭据文件。因为这种方式用于将新的范围反射(reflect)到访问 token 。当您在删除凭据文件后运行脚本时,将运行授权过程。因此,请检索代码并使用该代码检索访问 token 和刷新 token 。
  4. 请准备一个示例文本文件,文件名为sample.txt。因为您的脚本中使用了 media

示例脚本:

const drive = google.drive({ version: "v3", auth });
const script = google.script({ version: "v1", auth });

drive.files.create(
{
requestBody: {
name: "sampleDocument",
mimeType: "application/vnd.google-apps.document"
},
media: {
mimeType: "text/plain",
body: fs.createReadStream("./sample.txt")
}
},
(err, res) => {
if (err) {
console.error(err);
return;
}
script.projects.create(
{
requestBody: {
title: "sampleGASProject",
parentId: res.data.id
}
},
(err, res) => {
if (err) {
console.log(err);
return;
}
script.projects.updateContent(
{
scriptId: res.data.scriptId,
auth,
resource: {
files: [
{
name: "Code",
type: "SERVER_JS",
source: 'var obj = {"foo":"bar"}\n'
},
{
name: "appsscript",
type: "JSON",
source:
'{"timeZone":"America/New_York","exceptionLogging":"STACKDRIVER"}'
}
]
}
},
(err, res) => {
if (err) {
console.log(err);
return;
}
console.log("Done.");
}
);
}
);
}
);
  • 运行此示例脚本时,将创建新的 Google 文档作为 sampleDocument 的文件名,并创建新的 GAS 项目作为 sampleGASProject 的项目名称。
    • 脚本完成后,您可以在根文件夹中看到新的 Google 文档。当您打开 Google 文档并打开脚本编辑器时,您可以看到 var obj = {"foo":"bar"} 的脚本。

注意:

  • 很遗憾,如果您使用服务帐户,则无法使用服务帐户管理 GAS 项目。请小心这一点。所以请使用OAuth2。

引用文献:

在我的环境中,我可以确认示例脚本有效。但如果这在您的环境中不起作用,我深表歉意。此时,请检查API是否启用和/或其他环境。如果我误解了您的问题并且这不是您想要的方向,我深表歉意。

关于node.js - 使用 Node 创建带有内置对象的 Google 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59399410/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com