How to embed Node.js interpreter into C/C++?

You should first consider whether it would be sufficient to implement your application as a C++ module for Node and then glue the main part as a Node script.

Otherwise you may wish to "re-implement Node", by taking the core code as the example and removing the parts which you don't need (e.g. HTTP module) and then putting your components into it. The least painful way would be to do a sub-tree merge and ripping-out the build system, then adding prefixes in the build scripts to point to the directory where it lives. Then you can stop certain parts from being built. However Node's build system contains several parts and it may be quite a difficult job to do.

You can also try re-packaging Node with your stuff loaded by default and changing the name of the executable. However, that is just a more complex way of taking the first approach I have described, you can just install a script in /usr/bin/ which will go as:

  #!/usr/bin/node
  var myAppMain = require('libmyApp');
  myAppMain.withConfig(filename,
  function(err, cnf) {
     if (err) throw err; // parser or file access error
     cnf.evalMe();
  });

You can use a JSlint as your parser, then grep for dangerous calls and then eval(conf_script) or just use require(config.js), though you will need to add exports.someMethod = function (...) {...}. But require() is much safer in general, however you may wish to implement a pre-processor for your config which will substitute exports.someMethod = function (...) {...} instead of your functions and will append require('OnlyCallMySafeMethods') and reject any attempts to require('fs') or other lib which you may be afraid of letting the someone to use. This sort of safety is just an optional thing you may wish to have, it's all up to you really. Though I suppose you might want to do the bit with exports.someMethod = .... substitution and have one require('myAppConfigLib) added on the top so the user will just use you API plus anything they may wish to put into their script/config!

UPDATE: There is a quite useful comment on line 66 of src/node.js:

  // To allow people to extend Node in different ways, this hook allows
  // one to drop a file lib/_third_party_main.js into the build
  // directory which will be executed instead of Node's normal loading.

Please also note that the contents of src/ are being compiled to bytecode at build time.


I've build something close to what I think you're looking for:

https://github.com/ZECTBynmo/tacnode

It's a library that allows node.js to be linked statically into a C++ application. It's definitely not polished, but I've used it to launch simple node scripts.


Embedding Node.JS is now officially supported by a Node.JS fork JXcore. Embedding docs are available from this link.

Tags:

C++

C

Node.Js