javascript - 如何在 nodeJS 中将返回字节数组的 Bigtable HBase API 转换为整数或 float ?

标签 javascript arrays node.js hbase google-cloud-bigtable

我正在将 dataflow 中的数据写入 bigtable,需要从 NodeJS 检索数据,但意识到数据是字节数组。如何转换回整数或 float ?

键“\u0000\u0000\u0000\u0000”最初是 0,但我无法在我的 nodeJS 代码中正确输出它。

我已经使用 Buffer、bin2string、byteArrayToLong 尝试了以下方法,但它们都无法正常工作。下面是查询数据的代码。

async function query(table, start, end) {
  return new Promise((resolve, reject) => {
    table.createReadStream({
      start: start,
      end: end
    }).on('data', function(row) {
        for(var key in row.data.ch){
            console.log(JSON.stringify(key));               // Output: "\u0000\u0000\u0000\u0000"
            console.log(`bin2string: ${bin2string(key)}`);  // Output: bin2string:

            let keybuf = Buffer.from(key);
            console.log(keybuf);                            // Output: <Buffer 00 00 00 00>
            console.log(keybuf.toString('utf8'));           // Output:
            const utf16Buffer = Buffer.from(key,'utf16le'); // Output: <Buffer 00 00 00 00 00 00 00 00>
            console.log(utf16Buffer);
            console.log(utf16Buffer.toString());            // Output:
            console.log(byteArrayToLong(key));              // Output: NaN
        }
      // Nothing to do with data
      // We can measure the time needed to get the first row
    }).on('end', function(){
      resolve();
    });  
  });
}

function bin2string(array){
    var result = "";
    for(var i = 0; i < array.length; ++i){
        result+= (String.fromCharCode(array[i]));
    }
    return result;
}

function byteArrayToLong (byteArray){
    var value =0;
    for(var i=byteArray.length-1; i>=0; i--){
        value = value*256 + byteArray[i];
    }
    return value;
}

最佳答案

对于您的问题,我没有完整的答案,但我有一些建议。

Cloud Bigtable 数字都是“编码为 8 字节大端值的 64 位整数”(参见 here)。 Node.js longs“endian-ness”是系统特定的(参见 here )。 PHP 与 Cloud Bigtable 存在类似的问题(请参阅 here)。

在 Java 中,所有数值都是大端的。 HBase Bytes 类执行数字和字节之间的所有转换 (source code),并可能提供一些线索。

https://github.com/googleapis/nodejs-bigtable/issues 上发布问题可能令人愤怒以获得更好的解决方案。

关于javascript - 如何在 nodeJS 中将返回字节数组的 Bigtable HBase API 转换为整数或 float ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52783503/

相关文章:

javascript - 将数组十六进制颜色转换为数组 RGB 颜色

c++ - 数组下标错误的类型 'int[int]'无效

javascript - 使用 Node.js 读取、解析、迭代 JSON

javascript - 从数组中获取元素的困惑

javascript - NodeJS 不喜欢通行证 + Sequelize 登录

javascript - 如何在 Chrome 中调试 RequreJS 检索的脚本

javascript - 无法使用 google kms 生成有效的 jwt 签名

javascript - 我怎样才能扩展和收缩一个元素,使其在收缩状态下始终位于另一个元素之上?

c - 如何将扫描值推送到 C 中的堆栈?

node.js - 使用动态查询在 Node 中使用 Mongoose 更新多条记录