Converting N-API object to C++ basic data types through reading

I've been working on a N-API module by customizing the ObjectWrap boilerplate provided in generator-napi-module. So far, I have successfully passed an array containing objects with string, number, and boolean properties from native C++ code to JavaScript. However, I've encountered an issue when trying to extract a uint32_t value from a number property of one of these objects back in the native code.

Let's say we create an array of objects and pass it to JS:

Napi::Value ObjectWrapAddon::GetSomeList(const Napi::CallbackInfo& info){
  Napi::Env env = info.Env();
  native_struct_one *data = NULL;
  native_struct_two opts = { TRUE,FALSE,FALSE };
  int retVal = native_lib_method(&data, &opts);
  if(retVal!=OK) {
    return Napi::Array::New(env); // return empty array
  }
  Napi::Array arr = Napi::Array::New(env);
  uint32_t i = 0;
  do {
    Napi::Object tempObj = Napi::Object::New(env);
    tempObj.Set("someProp", data->someVal);
    arr[i] = tempObj;
    i++;
    data = data->next;
  } while(data);
  return arr;
}

And then we pass one of those objects to a native function:

Napi::Value ObjectWrapAddon::OtherMethod(const Napi::CallbackInfo& info){
  Napi::Env env = info.Env();
  Napi::Object obj = info[0].As<Napi::Object>();
  uint32_t temp = obj.Get("someProp").As<Napi::Number>();
  return Napi::Number::New(env, temp);
}

While the code compiles without errors, the OtherMethod() function throws an A number was expected error at

uint32_t temp = obj.Get('someProp').As<Napi::Number>()
.

What is the correct way to extract a native (C++) value from a property of a JS object?

Answer №1

Two key details were overlooked, leading to the functionality of this code:

  1. Inconsistency in the use of single and double quotes while working with Get/Set methods within Napi::Object. Ensuring matching quote types resolved this issue.
  2. The necessity of using the Uint32Value() method as outlined in the documentation (which was accidentally omitted), resulting in the corrected syntax:
    uint32_t temp = obj.Get("someProp").As<Napi::Number>().Uint32Value();

By addressing these oversights, the anticipated outcome is achieved.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Opening multiple dialogs in Jquery Dialog box

I have several images displayed on a single page. When each image is clicked, I want a dialog box to open. I currently have 6 instances of this setup in my HTML. However, when I click on an image, all 6 dialogs pop up with the same information as the first ...

data not populating in datagrid upon first load

I'm facing an issue where the data I'm trying to fetch using an API is not initially loading in my datagrid. I can retrieve the data successfully, but for some reason, it doesn't show up in the datagrid. The setup involves a common function ...

Warning: Next.js is throwing a hydration error because the server HTML does not include a matching <main> element within a <div>

I have been encountering hydration issues in my next.js application. After extensive troubleshooting, I have found that the culprit might be the higher order component called withAuth.js The error message displayed is: Warning: Expected server HTML to con ...

Activate Span element when image is clicked

To show and hide different span tags when clicking on specific images, you can use the following jQuery script: $("#img1").on('click', function() { $("#div1").fadeIn(); $("#div2,#div3").fadeOut(); }); $("#img2").on('click', functio ...

Using CSS on a randomly selected div that is chosen after dividing the main div each time it is clicked

Imagine a square box displayed as a "div" element. When you click on it, it splits into an n x n grid with each square having a random background color. However, the issue I am encountering is that I want to apply additional CSS to each of these randomly c ...

What is the best way to keep a checkbox unchecked after clicking cancel?

I'm working on a bootbox script that triggers a customized alert. I need the checkbox that triggers the alert to be unchecked when the user clicks cancel. Here is the checkbox when it's checked <div class="checkbox"> <label> ...

What are the best practices for utilizing the find_library function?

I have a collection of files structured like this: https://i.sstatic.net/fb2zS.png My current goal is to create an executable file, but I've encountered some roadblocks while attempting to do so during the creation of a makefile. I used CMake to cr ...

Switching perspective in express with Pug

Hello everyone, I'm still getting the hang of using Node.js with Express and Jade. I've successfully set up a basic 1 page app where a login page is displayed by default. Once the user logs in and is authenticated against a database, the function ...

Facing issues with jQuery and Bootstrap: ERR_CONNECTION_RESET

My jQuery and Bootstrap are causing issues and showing the following error message: GET net::ERR_CONNECTION_RESET GET net::ERR_CONNECTION_RESET Imports: jQuery: <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> ...

Tips for solving memory leaks in my vue.js / axios application?

I am facing an issue with a single page that displays rows from a table using inline vue.js script. The page fetches the list of rows on load and also fetches the table again when pusher events are received. Additionally, there is a modal window that allo ...

Signal check indicates that the Internet connection has been restored

One of the key requirements for my app is to load data into a database, which necessitates having an active Internet connection. I have been contemplating what to do in case of network failure - perhaps I can store the data locally on the device and synch ...

Filtering Tables with AngularJS

Currently, I'm experimenting with using angularJS to filter data in a table. My goal is to load the data from a JSON file that has a structure like this (example file): [{name: "Moroni", age: 50}, {name: "Tiancum", age: 43}, { ...

How can I transfer data from a MySQL callback function to a global variable?

I'm still in the learning stages of using nodejs and working on getting more comfortable with it. My goal is to retrieve a user from a database and store it in a variable, but I'm having trouble storing it globally. Though I can see that the conn ...

Using AngularJS, generate a JSON array with a specified key

Looking to create a JSON array structure with keys using AngularJS, but unsure how to push data in order to achieve this. The goal is to generate a JSON array based on the provided data below. $scope.category = [{"id": 20, "name": "vegetable"}, {"id": ...

Assistance with selecting elements using jQuery

I'm facing a challenge with a code that I cannot change. My goal is to introduce a selector that can choose (upon clicking) all elements below it until the next occurrence of the main element. The catch is that they are not nested, just stacked on top ...

Iterating through textboxes and buttons to trigger actions in JavaScript

Having an issue with JavaScript (or jQuery) where I can successfully input text and click a button on a page using the following script: document.getElementsByName('code')[0].value='ads0mx0'; document.getElementsByName('event&a ...

NodeJS reference copying problem

After encountering an issue where changes to the original object were being reflected in a copy due to JavaScript referencing, I followed recommendations and updated my code as follows: const originalData = {...docid[0][0].Record} // or const originalData ...

Utilizing Windows Azure and restify for node.js Development

I have an azure website with a URL like: . In my server.js file, I have the following code: var restify = require('restify'); function respond(req, res, next) { res.send('hello ' + req.params.name); next(); } var server = restify ...

Assign a CSS class to a DIV depending on the vertical position of the cursor

The website I am currently developing is located at Within the site, there is a collection of project titles. When hovering over a project title, the featured image is displayed directly below it. I would like to change the positioning of these images to ...

How can I generate identical pseudo-random number sequences using the same seed across various platforms in C/C++ programming?

In search of a stand-alone solution that does not require additional libraries. The main focus is on performance, as it will be used within a high-performance loop. This might mean sacrificing some degree of randomness for efficiency. ...