c++node.jsnode.js-addon

Node-Addon-Api Pass Array As Function Argument


I am trying to create a basic native node addon where a javascript array is passed from node and then processed in c++. The problem is I cannot figure out how to correctly pass the array. I can instantiate the array without issue but assigning it using info[0].as throws errors.

My c++ code is

#include <napi.h>

using namespace Napi;
using namespace std;

Value Add(const CallbackInfo& info) 
{
  Env env = info.Env();


  Array result = Napi::Array::New(env);
  Array a = info[0].As<Array>;

  double arg1 = info[1].As<Number>().DoubleValue();
  Number num = Napi::Number::New(env, 2 + arg1);

  return num;
}

The error I am getting is

../cppsrc/main.cpp: In function ‘Napi::Value Add(const Napi::CallbackInfo&)’:
../cppsrc/main.cpp:12:21: error: conversion from ‘<unresolved overloaded function type>’ to non-scalar type ‘Napi::Array’ requested
   Array a = info[0].As<Array>;
             ~~~~~~~~^~~~~~~~~

What is the correct way to pass an array to c++? Is it even possible?


Solution

  • This works for me:

    void runSetPropertyAsyncWorker(const CallbackInfo& info) 
    {
        std::string path = info[0].As<Napi::String>();
        int property = info[1].As<Number>();
        int dataSize = info[2].As<Number>();
        Array b = info[3].As<Array>();
        for(int i = 0; i<b.Length(); i++)
        {
          Napi::Value v = b[i];
          if (v.IsNumber())
          {
            int value = (int)v.As<Napi::Number>();
            ...
            ...
          }
        }
    
        ...
        ...
    
        Function callback = info[4].As<Function>();
        AsyncWorker* asyncWorker = new SetPropertyAsyncWorker(callback, ...);
        asyncWorker->Queue();
    }