Convert buffer to array

Ata picture Ata · Aug 9, 2013 · Viewed 45k times · Source

I am setting memcached with

$memcached->set("item" , ["1" => "hello"]);

anything work in PHP ,

In Node.js with memcached plugin , I get a buffer instead of array in result

<Buffer 61 3a 25 61 34 3a>

I can not convert such buffer to array

In Node.js :

memcached.get("item" , function(err, data) {
  console.log(data);
}

Do you have any way ?

Answer

user4584267 picture user4584267 · Jun 3, 2017

arr = [...buffer]

ES6 introduced a lot of other features, besides buffers.

You can even easily append like this:

arr.push(...buffer)

The ... operator expands enumerables such as arrays and buffers when used in array. It also expands them into separate function arguments.


Yes, it's also faster:

... : x100000: 835.850ms

Slice call from prototype : x100000: 2118.513ms

var array,
    buffer = new Buffer([1, 4, 4, 5, 6, 7, 5, 3, 5, 67, 7, 4, 3, 5, 76, 234, 24, 235, 24, 4, 234, 234, 234, 325, 32, 6246, 8, 89, 689, 7687, 56, 54, 643, 32, 213, 2134, 235, 346, 45756, 857, 987, 0790, 89, 57, 5, 32, 423, 54, 6, 765, 65, 745, 4, 34, 543, 43, 3, 3, 3, 34, 3, 63, 63, 35, 7, 537, 35, 75, 754, 7, 23, 234, 43, 6, 247, 35, 54, 745, 767, 5, 3, 2, 2, 6, 7, 32, 3, 56, 346, 4, 32, 32, 3, 4, 45, 5, 34, 45, 43, 43]),
    iter = 100000;

array = buffer;

console.time("... : x" + iter);
for (var i = iter; i--;) array = [...buffer]
console.timeEnd("... : x" + iter);

console.time("Apply/call/etc : x" + iter);
for (var i = iter; i--;) array = Array.prototype.slice.call(buffer, 0)
console.timeEnd("Apply/call/etc : x" + iter);