I've an application written in C. I would like to execute user defined scripts written in JavaScript in this application and allow these scripts to work with my internal C variables mapped to JavaScript namespace.
Is it possible to use NodeJS to compile it as a scripting engine?
I know that I can do vice versa: run NodeJS and use my C code as a library for NodeJS with proper binding of C variables to JS. But this is not acceptable, since my application has a GUI and many other modules that are included as libs and it would be hard to rewrite the code to run as a NodeJS lib.
I also don't want to run NodeJS as an external executable each time I need to run a script due to performance reasons. I need to keep NodeJS in memory and run scripts in the same namespace during the whole process cycle.
Maybe there is some special edition of NodeJS intended for such purpose? Or I can compile it as such?
Here is an example executing some javascript using v8:
int main(int argc, char* argv[]) {
// Create a string containing the JavaScript source code.
String source = String::New("'Hello' + ', World'");
// Compile the source code.
Script script = Script::Compile(source);
// Run the script to get the result.
Value result = script->Run();
// Convert the result to an ASCII string and print it.
String::AsciiValue ascii(result);
printf("%s\n", *ascii);
return 0;
}
What you need is V8 javascript engine. Take a look here for more details...
This document discusses these concepts further and introduces others that are key to embedding V8 within your own C++ application.
What you can use nodejs for is perhaps to look at it's source code on how to build on top of V8 engine.
And here is a quick example.
Why not explore the internals of Node and sort of "copy" what it's doing. Then you can build your app on top of V8. Node.JS is, after all, just a layer on top of V8 and several libraries (I/O) to provide additional functionality.