我在两个单独的Google桶中有file.txt和下面的目录结构:
桶-a/文件夹-1/文件夹-a
桶-a/文件夹-2/文件夹-b
桶-a/文件夹-3/文件夹-c
桶-b(没有子文件夹)
到目前为止,我的功能如下所示:
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
任何指点都会很有帮助。
发布于 2019-11-10 13:21:23
首先,移动对象在云存储中是不可能的。即使某些库实现了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!!
};和package.json
{
"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"
}
}https://stackoverflow.com/questions/58784133
复制相似问题