简体   繁体   English

使用 node.js 将 JSON 上传到 s3 的问题

[英]Issues Uploading JSON to s3 using node.js

I am new to amazon s3 and am trying to use node.js to upload JSON into a file.我是 amazon s3 的新手,正在尝试使用 node.js 将 JSON 上传到文件中。 My object is users , and it has a bunch of keys and values in it.我的 object 是users ,里面有一堆键和值。 Here is how I'm uploading it:这是我上传它的方式:

 s3.putObject({Bucket: 'currenteventstest',Key: 'users.json',Body: users, ContentType: "application/json"});

However, when I re download it, it's just an empty object.但是,当我重新下载它时,它只是一个空的 object。

Adding a callback function fixes the problem:添加回调函数解决了这个问题:

s3.putObject({
  Bucket: 'currenteventstest',
  Key: 'users.json',
  Body: JSON.stringify(users),
  ContentType: "application/json"},
  function (err,data) {
    console.log(JSON.stringify(err) + " " + JSON.stringify(data));
  }
);

I don't have enough reputation to comment, but for what its worth with the new aws-sdk version you can use the promise chain when posting the JSON instead of a callback:我没有足够的声誉来评论,但是对于新 aws-sdk 版本的价值,您可以在发布 JSON 而不是回调时使用承诺链:

try{
   await s3.putObject({
        Bucket: 'currenteventstest',
        Key: 'users.json',
        Body: JSON.stringify(users),
        ContentType: 'application/json; charset=utf-8'
    }).promise();
}
catch(e){
   throw e
}

JSON.stringify is the way to create a JSON file on S3. JSON.stringify是在 S3 上创建 JSON 文件的方法。

AWS accepts serialized JSON string as Body. AWS 接受序列化的 JSON 字符串作为正文。

s3.putObject({
    Bucket: 'currenteventstest',
    Key: 'users.json',
    Body: JSON.stringify(users),
    ContentType: 'application/json; charset=utf-8'
});

I had an ES6 Map in my data, which gets stringified to empty by default.我的数据中有一个 ES6 Map,默认情况下它被字符串化为空。 I had to refer to below answer to address the issue by manually adding a replacer function to the JSON.Stringify我不得不参考下面的答案来解决这个问题,方法是手动将replacer器 function 添加到JSON.Stringify

How do you JSON.stringify an ES6 Map? 你如何 JSON.stringify ES6 Map?

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

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