将 JSON 字符串上传到 Google 云存储而不需要文件

Upload JSON string to Google Cloud Storage without a file

我的情况是,当我从其他来源接收数据作为 JSON 字符串时,我想将此字符串上传到 Google Cloud Storage 而无需将此字符串写入本地文件并上传这个文件。有什么办法可以做到这一点。谢谢你。 看起来像下面的代码

storage
  .bucket(bucketName)
  .upload(jsonString, { destination: 'folder/test.json' })
  .then(() => {
    console.log('success');
  })
  .catch((err) => {
    console.error('ERROR:', err);
  });

所以我预计 Google 云存储会有一个文件 test.json,其中包含来自 jsonString

的内容

看起来这个场景已经在另一个 中解决了。

两个答案看起来都不错,但使用 file.save() 方法(第二个答案)可能会更容易。您可以找到此方法的描述和另一个示例 here

希望对您有所帮助。

万一有人在这里寻找答案的片段,它正在使用 file.save()。请注意,数据应该是 stringfy。

const storage = new Storage();

exports.entry_point = (event, context) => {
  var data = Buffer.from(event.data, 'base64').toString();
  data = transform(data)
  var datetime = new Date().toISOString()
  var bucketName =  storage.bucket('your_filename')
  var fileName = bucketName.file(`date-${datetime}.json`)
  fileName.save(data, function(err) {
  if (!err) {
    console.log(`Successfully uploaded ${fileName}`)
  }});

  //-
  // If the callback is omitted, we'll return a Promise.
  //-
  fileName.save(data).then(function() {});
};

扩展@ch_mike的回答

const { Storage } = require('@google-cloud/storage')
const storage = new Storage()
const bucket = storage.bucket(bucketName)

const saveJsonFile = (data) => {
   const timestamp = new Date().getTime()
   const fileName = `${timestamp}.json`
   const file = bucket.file(fileName)
   const contents = JSON.stringify(data)
   return file.save(contents)
}