首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >事件驱动的带有Google函数的Node文件复制到不同的google桶

事件驱动的带有Google函数的Node文件复制到不同的google桶
EN

Stack Overflow用户
提问于 2019-11-09 22:33:43
回答 1查看 793关注 0票数 0

我在两个单独的Google桶中有file.txt和下面的目录结构:

桶-a/文件夹-1/文件夹-a

桶-a/文件夹-2/文件夹-b

桶-a/文件夹-3/文件夹-c

桶-b(没有子文件夹)

到目前为止,我的功能如下所示:

代码语言:javascript
复制
var fs = require('fs')
var path = require('path');

exports.helloGCS = (event, context) => {

  const gcsEvent = event;
  const sourceFilePath = path.format(gcsEvent)
  const sourceFileOnly = path.basename(sourceFilePath)
  const sourcePathOnly = path.dirname(sourceFilePath)
  const sourceFolder = path.basename(path.dirname(sourceFilePath))
  const destFilePath = path.join('bucket-b' , sourceFolder , sourceFileOnly)

  console.log(`Processing file: ${destFilePath}`);
};

如果file.txt被上传到桶-a/文件夹-2/文件夹-b,并且它还不存在于目标桶中,我想将它复制到桶-b的destFilePath中。我只是不知道如何复制触发事件的文件,也不知道如何将目标设置为新的文件路径和桶,即:

桶-b/文件夹-b/file.txt

任何指点都会很有帮助。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-11-10 13:21:23

首先,移动对象在云存储中是不可能的。即使某些库实现了moverename操作,底层的API调用也是copy,然后是delete

对于复制对象,有几种语言的示例( 这里 )。

不要担心文件夹的存在与否。你想知道秘密吗?云存储中不存在文件夹。路径只是文件的元数据,帮助“人”更好地组织对象。因此,即使不存在,也可以随意设置您想要的路径。

最后,为了获得与源文件一致的正确文件夹,您必须使用字符串拆分和子字符串。

更新

我的密码有效了。我坚持您的要求,,但是如果文件被拖到桶的根上是不安全的!

这里是index.js

代码语言:javascript
复制
const {Storage} = require('@google-cloud/storage');
const {path} = require('path');

exports.helloGCS = (event, context) => {
  const storage = new Storage();
  const gcsEvent = event;
  const sourceFileBucket = gcsEvent.bucket
  const sourcePathOnly = gcsEvent.name
  const sourceFolder = sourcePathOnly.split('/').slice(-2) //Keep only the file name and the last folder name in the path. Not safe!!

  storage
  .bucket(sourceFileBucket)
  .file(sourcePathOnly)
  .copy(storage.bucket('<Bucket dest>').file(sourceFolder[0] + '/' + sourceFolder[1])); //this is not safe!!

};

和package.json

代码语言:javascript
复制
 {
    "name": "my_package",
    "description": "",
    "version": "1.0.0",
    "main": "index.js",
    "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "dependencies" : { 
      "@google-cloud/storage": "^4.1.1"
    }
  }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58784133

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档