javascript 将流解析为 Nodejs 中的对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14096124/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:42:06  来源:igfitidea点击:

Parse stream to object in Nodejs

javascriptnode.jsstreamamazon-web-servicesamazon-s3

提问by Samuel Ondrek

I am trying Get an object from Amazon S3 storagein Node.Js.

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

And this perfectly works when I am saving it to a file.

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

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);
    });

};

In. helloaa.json is:

在。helloaa.json 是:

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

But. I don't want to write data to file on my disk.

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

I want parse this json to object with JSON.parse();

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

When I print object there with:

当我在那里打印对象时:

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

In console is this:

在控制台是这样的:

{"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":

What is it?

它是什么?

How can I parse it?

我该如何解析它?

Is it stream?

是流吗?

Can I save stream to object in NodeJs?

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

回答by hunterloftis

Have you tried data.Body.toString()?

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

回答by vt_todd

I had to parse the JSON after converting to string:

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

    var fileContents = data.Body.toString();
    var json = JSON.parse(fileContents);
    console.log(json);