2

I am using node 6.9.1 and I try to create a cpp addon that will create Node Buffer objects. After some research I came up with the following code:

#include <node.h>
#include <node_buffer.h>
#include <v8.h>

using v8::Local;
using v8::Object;
using v8::HandleScope;
using v8::Isolate;

Local<Object> create_buffer(Isolate* isolate, char* rawData, int length) {
  HandleScope scope(isolate);
  Local<Object> buf = node::Buffer::New(
    isolate,
    rawData,
    length).ToLocalChecked();
  return buf;
}

which I use as follows:

Local<Value> buff = create_buffer(isolate, rawData, length);
const unsigned argc = 1;
Local<Value> argv[argc] = { buff };
cb->Call(Null(isolate), argc, argv);

This code compiles just fine but causes an error when I access the .length property of the buffer I get through the callback:

Security context: 0x9d84c7cfb51 <JS Object>#0#

I found several tutorials but all of them use an earlier version of v8/node api and I cannot find any info what is a proper way to create buffer in the recent Node versions. Also it is possible that I have made a mistake somewhere. Thanks in advance if you can guide me in the right direction.

1
  • It seems I should just use nan Commented Jan 20, 2017 at 15:05

1 Answer 1

1

The best way is to use NAN's NewBuffer helper:

Nan::MaybeLocal<v8::Object> mybuffer = Nan::NewBuffer(size);
Nan::MaybeLocal<v8::Object> mybuffer = Nan::NewBuffer(mydata, size);

Node's node_buffer.h also has a public constructor, but it's not necessarily consistent across versions.

I'm not positive, but your error might be because you've freed the raw data used to construct the buffer?

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, with Nan it works great. I wonder when do I how to free my data? Can I free the data after I created a buffer? Or should I free it when the buffer is not needed at all?
@OleksiiRudenko If you use these helpers, then v8 owns the memory and will free it for you when the Buffer is GC'ed. There's a third form I didn't list (click the link) that lets you pass a FreeCallback if you need more control. Finally, you can use Nan::CopyBuffer (same doc page), which will memcpy the data so that you retain control of the original data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.