Reputation: 4329
A bit of a strange one this...
I've written a NodeJS native module that works well most of the time, but the class contains a method that breaks the module when it's run in a context that shares memory.
Roughly speaking, the module opens an IO server, but there's a bug that requires me to open and close the IO server to retrieve a particular value... When I perform this action, any pointers found to reference old IO server object obviously break/segfault (a 'scribble space' error, right?).
To work around this problem, I currently use NodeJS's child_process.fork() to run the errant method in an isolated context, and pass messages between the main process and the forked process to have the program run as required (i.e. I call the method inside the forked process, and use 'process.on("message", ...)' to retrive the result). This works well, but it feels like a very expensive hack...
For the record, I've tried using a Libuv thread to run the method, but I encounter the same problem. I'm guessing that's because the function call is still made in shared memory.
Is there anyway for me to run a small portion (or more...) of C/C++ code in a 'NodeJS style' process using C++?
Upvotes: 1
Views: 1537
Reputation: 10818
You can't tear off a single method cleanly into a new process. Probably what you should do is write a tiny bit of C++ glue as a node module and start a separate process as a server. Then you can communicate with that process via sockets (or unix sockets, or whatever works on your target OS).
If you're really running into memory corruption bugs, you will want to isolate the bad code into a separate process so when it goes down it won't take out the main node process -- just the tiny server that supports what you need.
Writing C++ extensions to node is quite easy - I'm a seasoned C++ programmer new to javascript and I started doing it just recently. A couple of tips there--
Use NaN (Native abstractions for Node) https://github.com/rvagg/nan to protect you against changes in the 0.10 -> 0.11 -> 0.12 migration
Work through the tutorial ( http://nodejs.org/api/addons.html ) the "hard way", that is, typing in each example and building it.
Use a C++ unit test library
An example of a project that I'm polishing up (but works reasonably well already) is here : https://github.com/smikes/inchi InChI is a standard for representing molecules; this makes the C/C++ InChI library usable from node.
Upvotes: 2