Creating a Proper Buffer in a Node C++ Addon
Despite the wordy title, it’s actually a fairly simple problem, with a fairly simple solution.
“Fantastic! I’ll rock one of those buffers and simply return
bufferObject->handle_!”, I hear you exclaim. Not so fast stud.
If the client were to use this Buffer, they’d get a nasty surprise. It’s not a Buffer. You see, Node.js has re-implemented Buffers since 0.2. The Buffer you’re playing with from node_buffer.h is actually a SlowBuffer. As the name implies, it’s working directly on the heap-allocated memory chunk, so alot of operations on it are quite inefficient. Worse still, the interface provided on SlowBuffer is actually different to the Node.js documentation. Allow me to explain.
The Buffer you’re used to dealing with from Node.js user code actually originates from buffer.js. These Buffers are actually just “views” on a proper SlowBuffer, so operations like slicing are literally as quick as allocating a new Buffer object that views the SlowBuffer at a different offset and max length.
So how do you create one of these badboys from C++ to pass directly back to JS calling code? Glad you asked. Like so:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
And that’s all folks!