我正在尝试创建存储桶并将文件上传到存储桶。最初我有这样的代码:
storage
.createBucket(bucketName)
.upload(tempFilePath)
但这给了我错误:
TypeError: storage.createBucket(...).upload is not a function
我认为这意味着我不了解要存储的API。我本以为createBucket调用返回“ bucket”对象,然后可以将其用于上载到该对象。是我滥用承诺还是误解了存储NodeJS API?
谁能帮助我了解如何编写具有以下属性的函数:
完整的代码在这里:
exports.writeChunk = functions.firestore
.document('data/{userId}/data/{eventId}/chunks/chunk')
.onUpdate((change, context) => {
const projectId = 'chunk-abcdef';
const Storage = require('@google-cloud/storage');
const storage = new Storage({
projectId,
});
const data = change.after.data();
// data = { "chunk" : "abcdef" }
if( data && data.chunk ) {
let bucketName = context.params.eventId;
let fileName = `${context.params.eventId}-${context.params.userId}.txt`;
const tempFilePath = path.join(os.tmpdir(), fileName);
console.log( `Writing out to ${tempFilePath}` );
fs.writeFileSync(tempFilePath, data.chunk );
storage
.createBucket(bucketName)
.then( () =>
storage
.bucket(bucketName)
.upload(tempFilePath)
.then( () => fs.unlinkSync(tempFilePath) )
.catch( err => console.error('ERROR inside upload', err))
)
.catch(err => console.error('ERROR inside createBucket', err) );
}
else {
console.log( "Nope!", data );
}