简体   繁体   English

在node.js中使用字节数组数据以及如何处理它

[英]working with byte array data in node.js and how to process it

I need the entire byte array data fetched from a socket and after that I need to insert it into a database a BLOB. 我需要从套接字获取的整个字节数组数据,然后需要将其插入数据库BLOB。 Do not ask me why I am not formatting the data from byte array, because I need to work with that structure. 不要问我为什么不格式化字节数组中的数据,因为我需要使用该结构。

I am storing the byte array data into a js array. 我将字节数组数据存储到js数组中。 I tried to store it within a buffer object but I get errors when I try to write the byte array data into the buffer because it can convert it. 我试图将其存储在缓冲区对象中,但是当我尝试将字节数组数据写入缓冲区时会出错,因为它可以转换它。

My question is how is the easiest way to work with byte array in js. 我的问题是在js中使用字节数组的最简单方法是什么。 I have the following code: 我有以下代码:

var buff =[];
sock.on('data', function(data) {
    buff.push(data);
})

sock.on('end', function() {
    console.log(data) // [<Byte Array>,<Byte Array>, ...]
});

Basically I want to insert my data as [] not as [,, ...]. 基本上,我想将数据插入为[]而不是[,, ...]。 What is the best solution for my problem? 什么是我的问题的最佳解决方案?

Depending on your database interface you might be able to stream each element of your JS array as a separate chunk. 根据您的数据库接口,您也许可以将JS数组的每个元素作为独立的块进行流式传输。

[Update] It looks like node.js now provides a Buffer.concat(...) method to concatenate a bunch of buffers into a single one (basically replacing the "buffertools" library I mention below). [更新]看来node.js现在提供了Buffer.concat(...)方法,将一堆缓冲区连接到一个缓冲区中(基本上替代了我在下面提到的“ buffertools”库)。

var buffers = [];
sock.on('data', function(data) {
  buffers.push(data);
}).on('end', function() {
  var bytes = Buffer.concat(buffers); // One big byte array here.
  // ...
});

[Original] Alternatively, you could use the buffertools module to concatenate all of the chunks into a single buffer. [原始]或者,您可以使用buffertools模块将所有块连接到单个缓冲区中。 For example: 例如:

var buffertools = require('buffertools');
var buff = new Buffer();
sock.on('data', function(data) {
  buff = buff.concat(data);
}).on('end', function() {
  console.log(buff); // <Byte Array>
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM