【问题标题】:How to save data from app engine to datastore google cloud javascript如何将数据从应用引擎保存到数据存储谷歌云 javascript
【发布时间】:2020-04-26 18:00:21
【问题描述】:

我是 GCP 的新手,我很难理解它的文档。我在 App Engine 上部署了我的网络应用程序。当我在本地运行我的应用程序时,我将一些数据保存在 JSON 文件中,这非常完美。现在我需要将来自客户端的 JSON 保存到谷歌云上的某个地方。

根据我的研究,我需要将数据存储在数据存储中。我需要一些清晰的示例和解释来了解如何将数据从 App Engine 存储到 GCP 中的数据存储。 基本上我正在寻找一种方法来存储我的 JSON 以便稍后将其传递给另一个应用程序。 我感谢任何帮助或建议。

 const port = process.env.PORT || 8000;
 app.use(express.static(__dirname + '/www'));

 app.listen(port);
 console.log('working on port '+ port);

 app.use(express.json({limit:'1mb'}));
 app.post('/api', (request, response) => {

     var ressult = JSON.stringify(request.body);

     //creating my JSON file
     fs.appendFile('Result.json', ressult +  "\n", (err) => { 

     if (err) throw err; 
 })     

});

【问题讨论】:

    标签: javascript node.js json google-app-engine google-cloud-datastore


    【解决方案1】:

    首先是基础知识:

    您需要以下内容来初始化客户端:

    // Imports the Google Cloud client library
    const {Datastore} = require('@google-cloud/datastore');
    
    // Creates a client
    const datastore = new Datastore();
    

    然后创建一个基本实体:

    async function quickstart() {
      // The kind for the new entity
      const kind = 'Task';
    
      // The name/ID for the new entity
      const name = 'sampletask1';
    
      // The Cloud Datastore key for the new entity
      const taskKey = datastore.key([kind, name]);
    
      // Prepares the new entity
      const task = {
        key: taskKey,
        data: {
          description: 'Buy milk',
        },
      };
    
      // Saves the entity
      await datastore.save(task);
      console.log(`Saved ${task.key.name}: ${task.data.description}`);
    }
    quickstart();
    

    现在您可以创建基本实体,您有不同的选择。如果 JSON 对象不太大,您可以将其作为值放入实体中(将其存储为文本)

    或者更好的方法是使用类似这样的方式将其存储为数组:

      testArrayValue() {
        // [START datastore_array_value]
        const task = {
          tags: ['fun', 'programming'],
          collaborators: ['alice', 'bob'],
        };
        // [END datastore_array_value]
    
        return this.datastore.save({
          key: this.incompleteKey,
          data: task,
        });
      }
    

    根据您的 JSON,您甚至可能想要创建嵌套数组,但逻辑是相同的。

    您也可以改用 Cloud Storage,只需将 JSON 文件视为对象即可。所以你需要把它存储在GAE的/tmp目录中,然后上传到bucket中。然后在另一边,将其下载到该应用程序的 /tmp 目录,并将其作为 JSON 文件处理。这里是basics on how to get started with Cloud Storage

    【讨论】:

      猜你喜欢
      • 2013-05-17
      • 2014-10-21
      • 1970-01-01
      • 1970-01-01
      • 2020-10-05
      • 1970-01-01
      • 2014-10-30
      • 1970-01-01
      • 2018-05-09
      相关资源
      最近更新 更多