在 Node.js 附加代码中使用 Nan 创建数组

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

我正在编写 Node 附加组件并尽可能多地使用 nan 库来编写代码。 Node 项目推荐它,因为它可以让你编写与不同版本的 v8 和 node 兼容的代码。

然而,在查看他们的 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 部分后,API 会更好地处理这个问题。

我是不是漏掉了什么?

如果您查看 the V8 documentation,您会发现 v8::Arrayv8::Object 的子集。鉴于此,您可以使用

创建一个数组
Nan::New<v8::Array>();

您可以参考 v8::Array 文档了解更多详情。

在寻找一些相关问题的解决方案时,我发现 this repository 其中有一些非常好的工作示例。

我只是在这里指出与数组相关的转换以供快速参考。

在参数中接收数组:

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 一个数组:

//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

具体的解决方法可以参考here