Сохранить содержимое в файле хранилища Google - PullRequest
0 голосов
/ 30 марта 2020

Я пытаюсь сохранить сгенерированный файл из оперативной памяти JSON в хранилище Google с помощью Nodejs.

Процесс сохранения в 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

1 Ответ

0 голосов
/ 30 марта 2020

Я нашел этот пример в официальном репозитории Node.js GCP .

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]
}

Я думаю, что это связано с контекстом функции asyn c, но если Вы используете метод GCP, это должно работать нормально

...