繁体   English   中英

谷歌云存储删除特定路径中的文件 Node.js

[英]Google Cloud Storage Delete file in a specific path Node.js

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

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');

它因同样的错误而失败。

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

确保:

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")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM