使用Google Functions和Node JS 10复制整个源文件夹,而不只是触发器文件

问题描述 投票:1回答:2

需要调整以下代码,以便它复制整个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 = 'cgi-transfer-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 = 'cgi-transfer-test'

    storage
    .bucket(sourceFileBucket)
    .file(sourcePathOnly)
    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}`);  
}
node.js google-cloud-platform google-cloud-functions google-cloud-storage
2个回答
0
投票

您可以调用getFiles()在目录中建立文件列表,然后复制文件。这样的事情(您可能需要针对自己的情况进行修改):

getFiles()

0
投票

您可以复制目录前缀的所有文件

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

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

请注意,每次触发函数时,都会复制整个前缀匹配项。如果您在同一存储桶中进行复制,则可以创建指数无限循环!

注意:从数学上讲,我不知道无限的事物是否可以是指数的!

© www.soinside.com 2019 - 2024. All rights reserved.