如何在Javascript SDK中解码来自kinesis.getRecords的数据?

问题描述 投票:0回答:2

我正在尝试从 Kinesis 数据流获取数据:

function getRecord(shard_iterator) {

    var getRecParams = {
        ShardIterator: shard_iterator
    };

    kinesis.getRecords(getRecParams, function(err, result) {
            // Loop through all the packages
            for (var record in result.Records) {
                console.log(JSON.stringify(result.Records[record].Data));
                break; // just to see the first one
            }
            //if (result.NextShardIterator) getRecord(result.NextShardIterator);
    });
}

我看到的结果:

{"type":"Buffer","data":[123,34,73,110,112,117....,125]}

形成 AWS CLI 我知道

data
应该是 base64 编码的,但这里有些不同。那么我如何从我看到的
data
数组中获取信息?

请注意,浏览器中的不是 NodeJS,而是 Javascript。

amazon-kinesis aws-sdk-js
2个回答
4
投票

解决方案,最好将其包含在文档中:

var decoder = new TextDecoder("utf-8");
function getRecord(shard_iterator) {

    var getRecParams = {
        ShardIterator: shard_iterator
    };

    kinesis.getRecords(getRecParams, function(err, result) {
        if (err) {
            console.log("Error in getRecords() from the Kinesis stream.");
            console.log(err);
        } else {
            try {
                // Loop through all the packages
                for (var record in result.Records) {
                    data = result.Records[record].Data
                    decoded = JSON.parse(decoder.decode(data));
                    console.log(decoded);
                }
            } catch(err) {
                console.log("Error parsing the package.");
                console.log(err);
            }
            if (result.NextShardIterator) getRecord(result.NextShardIterator);
        }
    });
}

0
投票

我也遇到了类似的问题。就我而言,我只需将

JSON.stringify(result.Records[record].Data)
更改为
result.Records[record].Data.toString()

© www.soinside.com 2019 - 2024. All rights reserved.