node.js - 谷歌云函数 bucket.upload()

标签 node.js firebase google-cloud-platform google-cloud-functions google-cloud-storage

我正在尝试使用由 firebase 写入触发的谷歌功能将 pdf 文件从远程网站存档到谷歌云存储。

下面的代码有效。但是,此函数会将远程文件复制到存储桶根目录。

我想将 pdf 复制到存储桶的 pth:library-xxxx.appspot.com/Orgs/${params.ukey}

如何做到这一点?

exports.copyFiles = functions.database.ref('Orgs/{orgkey}/resources/{restypekey}/{ukey}/linkDesc/en').onWrite(event => {
    const snapshot = event.data;
    const params = event.params;
    const filetocopy = snapshot.val();
    if (validFileType(filetocopy)) {
        const pth = 'Orgs/' + params.orgkey;

        const bucket = gcs.bucket('library-xxxx.appspot.com')
        return bucket.upload(filetocopy)
            .then(res => {
            console.log('res',res);
            }).catch(err => {
            console.log('err', err);
        });
    }
});

最佳答案

让我先简要解释一下 GCS 文件系统的工作原理:如 documentation of Google Cloud Storage 中所述。 , GCS 是一个平面命名空间,其中不存在目录的概念。如果你有一个像 gs://my-bucket/folder/file.txt 这样的对象,这意味着有一个名为 folder/file.txt 的对象存储在gs://my-bucket的根目录,即对象名称包含/字符。控制台中的 GCS UI 和 gsutil CLI 工具确实产生了具有分层文件结构的错觉,但这只是为了让用户更加清晰,即使这些目录没有存在,并且所有内容都存储在“平面” namespace 中。

也就是说,如 the reference for the storage.bucket.upload() method 中所述,您可以指定一个包含 destination 字段的 options 参数,您可以在其中指定一个包含要使用的完整文件名的string

举个例子(注意两个函数的options参数区别):

var bucket = storage.bucket('my-sample-bucket');

var options = {
  destination: 'somewhere/here.txt'
};

bucket.upload('sample.txt', function(err, file) {
    console.log("Created object gs://my-sample-bucket/sample.txt");
});

bucket.upload('sample.txt', options, function(err, file) {
    console.log("Created object gs://my-sample-bucket/somewhere/here.txt");
});

因此,在您的情况下,您可以构建一个包含您要使用的完整名称的字符串(还包含您想到的“目录”结构)。

关于node.js - 谷歌云函数 bucket.upload(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49961149/

相关文章:

node.js - 如何获取 MongoDB collection.find() 的回调

java - android 截击超时错误

android - 无法解析 com.google.android.gms :play-services-measurement-base:[18. 0.0]

android - 使用 Retrofit 时,Firestore 时间戳为(秒 : 0, 纳秒:0)

javascript - Google Vision API 调用的 CORS 问题

python-3.x - 在 Google Build cloudbuild.yaml 中运行 pytest 以确定构建是否通过

google-cloud-platform - 无法使用服务帐户订阅 google pub 子主题

node.js - 从 cron 作业调用时,nodejs setTimeout 不起作用

node.js - 如何在服务器中使用 node-postgres?

ios - 如何检索 Firebase 数据库文件夹中的列表?