将内容保存到Google存储文件中

问题描述 投票:0回答:1

我试图通过Nodejs将内存中的JSON生成的文件保存到Google存储。

保存到GCS的过程运行良好,正在创建文件,但抛出错误。(因为我没有捕获到错误,所以该过程有效)。

据我所知,错误来自storage.bucket(bucket).file(filename)

如何避免例外?

   let file = storage.bucket('dev').file('widgets/test.json');
   file.setMetadata({
        contentType: contentType,',
        cacheControl: 'public,no-cache,max-age=0',
    });
    return await file.save(json.stringify(content))`

错误-UnhandledPromiseRejectionWarning: Error: No such object: dev/widgets/test.json

node.js google-api google-cloud-storage google-api-nodejs-client
1个回答
0
投票

我在Node.js Official GCP repo上找到了这个示例。

function main(bucketName = 'my-bucket', filename = './local/path/to/file.txt') {
  // [START storage_upload_file]
  /**
   * TODO(developer): Uncomment the following lines before running the sample.
   */
  // const bucketName = 'Name of a bucket, e.g. my-bucket';
  // const filename = 'Local file to upload, e.g. ./local/path/to/file.txt';

  // Imports the Google Cloud client library
  const {Storage} = require('@google-cloud/storage');

  // Creates a client
  const storage = new Storage();

  async function uploadFile() {
    // Uploads a local file to the bucket
    await storage.bucket(bucketName).upload(filename, {
      // Support for HTTP requests made with `Accept-Encoding: gzip`
      gzip: true,
      // By setting the option `destination`, you can change the name of the
      // object you are uploading to a bucket.
      metadata: {
        // Enable long-lived HTTP caching headers
        // Use only if the contents of the file will never change
        // (If the contents will change, use cacheControl: 'no-cache')
        cacheControl: 'public, max-age=31536000',
      },
    });

    console.log(`${filename} uploaded to ${bucketName}.`);
  }

  uploadFile().catch(console.error);
  // [END storage_upload_file]
}

我认为这与异步函数的上下文有关,但是如果使用GCP方法,则应该可以正常工作

© www.soinside.com 2019 - 2024. All rights reserved.