0

I'm setting up a server that communicates with raw TCP using the 'net' module. I noticed something very strange: the data has a toArrayBuffer method, but it returns something that isn't an ArrayBuffer

net.createServer( function(socket) {
    socket.on('data', function(data) {
        var ab = data.toArrayBuffer();

        // prints "function ArrayBuffer() { [native code] }"
        console.log( ab.constructor );

        // prints 'false'
        console.log( ab.constructor == ArrayBuffer );
    });
}).listen(port);

Why is that the case? Is there something special about the array buffer that's coming from socket data?

ZECTBynmo
  • 3,197
  • 3
  • 25
  • 42

2 Answers2

1

Buffer#toArrayBuffer was introduced in v0.11.8 and it seems things are still a bit in flux; in fact, the method was recently removed due to memory leaks in V8. There's a thread on the v8-users mailing list detailing the issue.

In the meantime, you can convert to an ArrayBuffer via the method Jephron linked to.

As to your original question, I'm not sure why ab.constructor != ArrayBuffer; I'm not very familiar with the internals of V8, but you can see in the original code that it was returning a v8::ArrayBuffer.

Community
  • 1
  • 1
Michelle Tilley
  • 157,729
  • 40
  • 374
  • 311
  • 2
    it's quite possible that ArrayBuffer created in C++ are not instances of `ArrayBuffer` constructor. Anyway, `toArrayBuffer` method is badly broken and doesn't exist anymore – vkurchatkin May 27 '14 at 08:02
0

In NodeJS, buffers are represented by the Buffer object. socket.on('data') passes its callback a buffer object as seen here. Here's a thread that covers the conversion of Buffer to ArrayBuffer in Node

Convert a binary NodeJS Buffer to JavaScript ArrayBuffer

Community
  • 1
  • 1
Jephron
  • 2,652
  • 1
  • 23
  • 34