Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Nan to create array in Node.js add-on code

I'm writing Node add-on and using the nan library as much as I can for writing the code. It's recommended by the Node project because it lets you write code that's compatible with different version of v8 and node.

However after looking through their documentation many times, I haven't found any guidance on handling of arrays in the nan API. For basic tasks like processing arrays passed as arguments by the Javascript code, or instantiating new array objects in the add-on and return it to Javascript code. Are we supposed to directly work with v8::Array API. I wished the Nan::New part of the API would have handled this better.

Have I missed something?

like image 536
Jayesh Avatar asked Aug 30 '25 18:08

Jayesh


2 Answers

Searching for solutions to some related problems I have found this repository which has some very good working examples.

I'm just pointing out the Array related conversions here for quick reference.

Receive array in arguments:

Local<Array> array = Local<Array>::Cast(args[0]); //args[0] holds the first argument

for (unsigned int i = 0; i < array->Length(); i++ ) {
  if (Nan::Has(array, i).FromJust()) {
    //assuming the argument is an array of 'double' values, for any other type the following line will be changed to do the conversion
    double value = Nan::Get(array, i).ToLocalChecked()->NumberValue();

    Nan::Set(array, i, Nan::New<Number>(value + 1));
  }
}

Return an array:

//Assuming arr is an 'array' of 'double' values
Local<Array> a = New<v8::Array>(3);
Nan::Set(a, 0, Nan::New(arr[0]));
Nan::Set(a, 1, Nan::New(arr[1]));
Nan::Set(a, 2, Nan::New(arr[2]));

info.GetReturnValue().Set(a); //here 'info' is 'const Nan::FunctionCallbackInfo<v8::Value>& info' received in Nan Method defintion parameter

The specific solution can be found here.

like image 164
sha-1 Avatar answered Sep 02 '25 08:09

sha-1


If you look at the V8 documentation, you'll see that v8::Array is a subset of v8::Object. Given this, you can create an array with

Nan::New<v8::Array>();

You can reference the v8::Array documentation for more details.

like image 28
Mike Cluck Avatar answered Sep 02 '25 06:09

Mike Cluck