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 - 从脚本标记中的文本区域评估 Google Earth 代码

javascript - 对每个结果进行评估、iterateNext 和 setAttribute?

javascript - 如何重新导出另一个模块的默认导出?

java - 在 Java 中初始化对象类中的静态数组

node.js - 在 Node 项目上运行 make 命令

javascript - 如何将文件名从 multer 传递到另一个中间件?

javascript - 替换 HTML 然后将文档片段添加回 html

arrays - Bash 关联数组排序

javascript - 无法在 React.js 中使用 useState 进行渲染

node.js - 使用软件包安装程序安装node.js-dyld :Library not loaded error