Node.js 使用Google Cloud功能节点JS将事件驱动的文件复制到不同的Google bucket
我在两个单独的Google Bucket中有file.txt和以下目录结构: bucket-a/文件夹-1/文件夹-a bucket-a/文件夹-2/文件夹-b bucket-a/文件夹-3/文件夹-c 桶-b (没有子文件夹) 到目前为止,我的函数如下所示:Node.js 使用Google Cloud功能节点JS将事件驱动的文件复制到不同的Google bucket,node.js,google-cloud-functions,google-cloud-storage,Node.js,Google Cloud Functions,Google Cloud Storage,我在两个单独的Google Bucket中有file.txt和以下目录结构: bucket-a/文件夹-1/文件夹-a bucket-a/文件夹-2/文件夹-b bucket-a/文件夹-3/文件夹-c 桶-b (没有子文件夹) 到目前为止,我的函数如下所示: var fs = require('fs') var path = require('path'); exports.helloGCS = (event, context) => { const gcsEvent = eve
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被上传到bucket-a/folder-2/folder-b,并且它在目标bucket中不存在,我想将它复制到bucket-b的destFilePath。
我只是不知道如何首先复制触发事件的文件,也不知道如何将目标设置为新的文件路径和bucket,即:
bucket-b/folder-b/file.txt
任何指示都会非常有用 首先,在云存储中不可能移动对象。即使某些库实现了
move
或rename
操作,底层API调用也是copy
然后delete
对于复制对象,有几种语言的示例
不要担心文件夹是否存在。你想要一个秘密吗?云存储中不存在文件夹。路径只是文件的元数据,有助于“人”更好地组织对象。因此,即使不存在,也可以随意设置您想要的路径
最后,为了根据源文件获得正确的文件夹,必须使用字符串拆分和子字符串
更新
我的代码正在运行。我坚持你的要求,但是如果文件掉到桶的根上就不安全了强>
这里是index.js
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!!
};
您想复制GCS对象还是将GCS对象从一个存储桶/文件夹移动到另一个存储桶/文件夹?谢谢Kolban,我需要将其保存在源存储桶中,以便复制。谢谢Guillaume。是的,复制文件是我所追求的,因为我想在源bucket中保留一个版本。不幸的是,我尝试在您的链接中实现代码,但在尝试部署它时,它会给我以下错误:部署失败:加载用户代码时函数失败。错误消息:无法加载index.js文件中的代码。您的代码中有语法错误吗?详细堆栈跟踪:/srv/index.js:16等待存储^^^^^^^^^^^SyntaxError:await仅在异步函数中有效…删除
wait
。不确定在这种情况下是否需要异步处理。如果我删除wait,它看起来是这样的:storage.bucket(sourceBucketName).file(sourceFileOnly).copy(storage.bucket(destBucketName).file(destFileOnly));另一方面,如果我添加:const storage=new storage(),则得到“storage未定义”;我得到:“存储不是一个构造函数…”我测试了它,它在我这边工作。我分享了密码
{
"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"
}
}