node.js - 使用 Google Functions 和 Node JS 10 复制整个源文件夹而不仅仅是触发器文件

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

需要调整以下代码,以便它复制整个 sourceFolder 而不仅仅是事件文件本身,但不确定如何执行此操作。

const {Storage} = require('@google-cloud/storage');
const {path} = require('path');

exports.copyRenders = (event, context) => {
    const gcsEvent = event;
    const sourcePathOnly = gcsEvent.name



    const folderToWatch = ' ... folder on source bucket... '


// Process only if it's in the correct folder
  if (sourcePathOnly.indexOf(folderToWatch) > -1) {

    const storage = new Storage();
    const sourceFileBucket = gcsEvent.bucket
    const sourceFolder = sourcePathOnly.split('/').slice(-2) 
    const destFileBucket = 'trans-test'

    storage
    .bucket(sourceFileBucket)
    .file(sourcePathOnly)
    .copy(storage.bucket(destFileBucket).file(sourceFolder[0] + '/' + 
    sourceFolder[1])); 
  }
  console.log(`Processing file: ${sourcePathOnly}`);  
}

使用以下答案中的新代码:

const {Storage} = require('@google-cloud/storage');
const {path} = require('path');

exports.copyRenders = (event, context) => {
    const gcsEvent = event;
    const sourcePathOnly = gcsEvent.name



    const folderToWatch = ' ... folder on source bucket... '


// Process only if it's in the correct folder
  if (sourcePathOnly.indexOf(folderToWatch) > -1) {

    const storage = new Storage();
    const sourceFileBucket = gcsEvent.bucket
    const sourceFolder = sourcePathOnly.split('/').slice(-2) 
    const destFileBucket = 'trans-test'

    const options = {
        // Get the source path without the file name)
        prefix: sourcePathOnly.slice(0,sourcePathOnly.lastIndexOf("/")),
    };

    const [files] = storage.bucket(sourceFileBucket).getFiles(options);

    files.forEach(file => {
        file.copy(storage.bucket(destFileBucket).file(sourceFolder[0] + '/' + sourceFolder[1]));
        });
    }
    console.log(`Processing file: ${sourcePathOnly}`);  
}

最佳答案

您可以调用getFiles()在目录中构建文件列表,然后复制文件。像这样的东西(您可能需要根据您的场景进行修改):

const [ files ] = await storage.bucket(sourceFileBucket).getFiles({
  autoPaginate: false,
  prefix: sourceFolder
});

files.forEach(file => file.copy( ... ));

关于node.js - 使用 Google Functions 和 Node JS 10 复制整个源文件夹而不仅仅是触发器文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58934727/

相关文章:

database - Firebase 的喜欢/不喜欢功能

Flutter Firebase Cloud 函数无法调用

javascript - Cloud Functions for Firebase 在 Algolia 中索引 Firebase 数据库对象

python - 谷歌云函数抛出奇怪的错误

javascript - Express Route Handler 不会针对文件类型路径触发

node.js - 如何使用 pg-promise 在没有密码的情况下连接到 Postgres 数据库?

json - 对 int 转换感到困惑

go - GCP语音到文本和语音激活检测协同工作

node.js - heroku git 存储库的 URL 是什么?

google-cloud-platform - 谷歌计算引擎时区