31

我正在尝试从Node.Js 中的 Amazon S3 存储中获取对象。

当我将它保存到文件时,这非常有效。

amazon.getObject = function () {

    var options = {
        BucketName : 'mybucket',
        ObjectName : 'path/to/my.json',
        ResponseContentType : 'application/json'
    };

    s3.GetObject(options, function(err, data) {
        var fs = require('fs');
        var fd = fs.openSync('helloaa.json', 'w+');
        fs.writeSync(fd, data.Body, 0, data.Body.length, 0);
        fs.closeSync(fd);
    });

};

在。helloaa.json 是:

{
    "hello": 1,
    "world": 3
}

但。我不想将数据写入磁盘上的文件。

我想用 JSON.parse() 解析这个 json 对象;

当我在那里打印对象时:

    s3.GetObject(options, function(err, data) {
        console.log(JSON.stringify(data));
    });

在控制台中是这样的:

{"StatusCode":200,"Headers":{"x-amz-id-2":"N1gDLPam+fDCLWd9Q2NI62hizH7eXAjg
61oLYOkanLoSlqUlDl6tqasbfdQXZ","x-amz-request-id":"C53957DAF635D3FD","date"
:"Mon, 31 Dec 2012 00:11:48 GMT","last-modified":"Sun, 30 Dec 2012 23:22:57        "etag":"\"8677a54c9b693bb6fc040ede8cc6a\"","accept-ranges":"bytes","co
ntent-type":"application/json","content-length":"176","server":"AmazonS3"},
"Body":{"0":123,"1":10,"2":32,"3":32,"4":32,"5":32,"6":34,"7":105,"8":100,"
9":34,"10":58,"11":32,"12":49,"13":44,"14":10,"15":32,"16":32,"17":32,"18":

它是什么?

我该如何解析它?

是流吗?

我可以将流保存到 NodeJs 中的对象吗?

4

3 回答 3

60

你试过data.Body.toString()吗?

于 2012-12-31T03:21:35.230 回答
18

转换为字符串后,我必须解析 JSON:

    var fileContents = data.Body.toString();
    var json = JSON.parse(fileContents);
    console.log(json);
于 2016-03-15T23:49:39.607 回答
0

将解析后的响应转换为base64,然后可以直接用作HTML的图像标签中的源。可以通过 Amazon REST API 进行 Lambda 调用

const AWS = require('aws-sdk');
//*/ get reference to S3 client 
var s3 = new AWS.S3();
exports.handler = (event, context, callback) => {
    var params = {
  "Bucket": "bucket-name",
  "Key": "object-name"  
    };
    s3.getObject(params, function(err, data){
       if(err) {
           callback(err, null);
       } else {
           let image = new Buffer(data.Body).toString('base64');
           image = "data:"+data.ContentType+";base64,"+image;
           let response = {
        "statusCode": 200,
        "headers": {
            "Access-Control-Allow-Origin": "*",
            'Content-Type': data.ContentType
        },
        "body":image,
        "isBase64Encoded": true
    };
           callback(null, response);
    }
    });
    
};
于 2021-01-01T18:30:37.830 回答