Returning array of C++ wrapped objects to NodeJS and JavaScript using nan

Lately I had a hard time trying to figure out how to properly wrap simple C++ objects (like structs or so) with limited understanding of object-oriented JS. So I took some time (actually not so long, but sill) and found out that there are no classes in JS so constructing objects is quite tricky as it always use prototype function.

Don’t really like the idea, but well…

Anyway, it was not really straightforward at the beginning to wrap C++ object. A bit easier after figuring out all that function for objects creation. It ends up with creating new wrapping object that has a creating function (I have called it “constructor” using the same naming as in the documentation. My objects are read only (in fact it is a representation of serial devices) and all properties are also read only, so I had to create only getters, called accessors:

So the whole “constructor” template function looks like this:

Then for each getter you can create a method (I liked this way) or create one getter and use the name to distinguish return values. For me it looked like this:

So the last thing is to create the JS object from the C++ object and fill the array. First object creation:

When we do have this we just need to create an JavaScript array with nan and v8:

That’s all, final result looks like this in console:

As always you can see the whole code as a commit on the github:

https://github.com/killpl/obd_cougar/commit/84974d028f5b2669e41db8b4c0ecd54b3d4ebb1b

After finally resolving this problems it is time to go on with UART communication and sending some commands to ELM327 😉

Leave a Reply

Your email address will not be published. Required fields are marked *