【问题标题】:Google Cloud Storage Delete file in a specific path Node.js谷歌云存储删除特定路径中的文件Node.js
【发布时间】:2021-03-30 20:11:34
【问题描述】:

我正在尝试使用 Google Cloud Storage node.js(或 Firebase Storage 管理员)删除特定目录中的特定文件。这是我的尝试:

const { Storage } = require('@google-cloud/storage');
const storage = new Storage({
  projectId: projectId,
  keyFilename: 'serviceAccountKey.json'
});
const bucket = storage.bucket("bucket");
const file = bucket.file('path1/path2/filename');
file.delete().then(function(data) {
  const apiResponse = data[0];
  console.log(apiResponse);
}).catch(error => {
  console.log(error);
});

因为我的文件位于路径bucket/path1/path2/filename,所以它并不直接位于桶内。但是当我运行代码时,它会产生一个错误:

    {
      message: 'No such object: bucket/path1/path2/filename',
      domain: 'global',
      reason: 'notFound'
    }

我也试过

const bucket = storage.bucket("bucket/path1/path2/");
const file = bucket.file('filename');

同样的错误失败了。

我确实看过documentation。它没有提及有关删除特定目录中的文件的任何内容。在这种情况下,如何使用 node.js 删除我的 Google Cloud Storage 中特定目录中的特定文件?

【问题讨论】:

  • 桶是对象的容器。存储桶中的每个对象都有一个名称。 GCS 中的目录是幻觉……只有对象。名称中以“/”结尾的对象在逻辑上被视为目录。如果您使用 GCS 浏览器,对象的名称显示为什么。我认为您可能会尝试在存储桶中查找对象,并在不应该的情况下将存储桶名称添加到对象名称中。

标签: node.js google-cloud-storage firebase-storage


【解决方案1】:

确保:

1- 您传递了正确的存储桶名称

2- 从它的第一个目录开始的文件的全名,它应该类似于“read/test.txt”

3-该文件确实存在,因为您可能已删除然后重试,这种情况下该文件将不存在

你也可以试试这个代码示例:

function main(bucketName, filename) {
  
    // Imports the Google Cloud client library
    const {Storage} = require('@google-cloud/storage');
  
    // Creates a client
    const storage = new Storage();
  
    async function deleteFile() {
      // Deletes the file from the bucket
      await storage.bucket(bucketName).file(filename).delete();
  
      console.log(`gs://${bucketName}/${filename} deleted.`);
    }
  
    deleteFile().catch(console.error);
    // [END storage_delete_file]
  }

  main("my-bucket", "read/test.txt")

【讨论】:

  • 好的,我试一试。
猜你喜欢
  • 1970-01-01
  • 2021-01-12
  • 1970-01-01
  • 2023-02-13
  • 1970-01-01
  • 1970-01-01
  • 2022-12-09
  • 2014-08-29
  • 1970-01-01
相关资源
最近更新 更多