node. js calls the module instance developed by C++
- 2020-07-21 06:42:19
- OfStack
How to use C++ to interact with node? In the program of node, if the calculation of large amount of data is slow, it can use C++ to process, and then return to node through callback (in the form of callback). Let's review the 1 orthodox approach to developing native modules with C++
#include <node.h>
#include <v8.h>
using namespace v8;
// Here is the hello Function of the C++ implementation
Handle<Value> Method(const Arguments& args) {
HandleScope scope;
return scope.Close(String::New("world"));
}
// Here is the module initialization function, must have
void init(Handle<Object> exports) {
exports->Set(String::NewSymbol("hello"),
FunctionTemplate::New(Method)->GetFunction());
}
// The name and initialization function of this module are defined here
NODE_MODULE(hello, init)
This module, written in Node, looks like this:
exports.hello = function() {
return 'world';
};
In order to compile C++ For this module, we still need 1 a JSON The format of binding.gyp File to define the compilation details.
{
"targets": [
{
"target_name": "hello",
"sources": [ "hello.cpp" ]
}
]
}
node-gyp configure build is compiled directly.
node test.js:
var addon = require('./build/Release/hello');
console.log(addon.hello());
Just output the result.
So node can directly call C++ written procedures.
In ES32en. cc, we first create a function Method, which returns a string of "hello,world", then we create a function of init, which we call as an initializer
Finally, we bind this module to: NODE_MODULE(hello, init)
According to the official website, all node plug-ins must output an initialization function, which means that the following code must be in a fixed format in each module.
void Initialize (Handle<Object> exports);
NODE_MODULE(module_name, Initialize)
Where module_name must correspond to target_name in ES52en.gyp.
After compiling node-ES59en configure build, a new folder for build will be generated under the current file. By referring to the result of build in ES63en.js, we can call C++ written program.