How to use C + + and node interaction, in the node program, if there is a large amount of data calculation, slow processing, you can use C + + to handle, and then through the callback (callback form), back to node. Let's review the orthodox approach to developing native modules in C + +
#include <node.h>
#include <v8.h>
using namespace V8;
Here is the C + + implementation section of the Hello function
handle<value> method (const arguments& args) {
handlescope scope;
return scope. Close (String::new (' World '));
}
Here is the initialization function for the module, which must have
void init (handle<object> exports) {
exports->set ("Hello"),
Functiontemplate::new (method)->getfunction ());
This defines the name and initialization function of this module
node_module (Hello, init)
This module is written with node, and this is the case:
Exports.hello = function () {return
' world ';
};
To compile the C + + module, you need a JSON-formatted BINDING.GYP file to define the details of the compilation.
{
"targets": [
{
"target_name": "Hello",
"sources": ["Hello.cpp"]
}
]
}
The Execute NODE-GYP Configure build is compiled directly.
Node Test.js:
var addon = require ('./build/release/hello ');
Console.log (Addon.hello ());
The result is output.
So node can call a program written by C + + directly.
Explanation of the above program: in hello.cc, we first created a function method, which returns a string of "Hello,world", and then we create an init function, and as an initialization function, we call a function
At the end, we bind this module to: Node_module (Hello, init)
In the official website, all node plug-ins must output an initialization function, which means that the following code is required in every module, fixed format.
void Initialize (handle<object> exports);
Which module_name must correspond to the BINDING.GYP in the target_name on it.
After the Node-gyp configure build is compiled, a new folder of builds is generated under the current file. By referencing the result of this build in test.js, we can invoke the written program of C + +.