Let’s see how to write a node native module through an example. Of course, this article also serves the purpose of setting up the initial environment for future articles on Node-gyp.
Based on the node – addon – API
Nodejs plugin based on node-addon-API, using the node header file: #include
hello_world.cc
#include <node.h>
void Method(const v8::FunctionCallbackInfo<v8::Value>& args) {
v8::Isolate* isolate = args.GetIsolate();
args.GetReturnValue().Set(v8::String::NewFromUtf8(
isolate, "world").ToLocalChecked());
}
void Initialize(v8::Local<v8::Object> exports) {
NODE_SET_METHOD(exports, "hello", Method);
}
NODE_MODULE(NODE_GYP_MODULE_NAME, Initialize)
Copy the code
binding.gyp
{
"targets": [
{
"target_name": "hello_world",
"sources": [ "hello_world.cc" ]
}
]
}
Copy the code
index.js
const binding = require('./build/Release/hello_world');
console.log(binding.hello());
Copy the code
package.json
."scripts": {
"build": "node-gyp configure && node-gyp build"."run:demo": "node index.js"},...Copy the code
The overall structure
Run the following commands in sequence:
$ npm run build// Configure and build using Node-gyp$ npm run run:demo/ / run the DemoCopy the code
The output is as follows:
D:\Projects\node-addon-demo> NPM run run:demo > [email protected] run:demo > node index.js worldCopy the code
Attached GitHub address: w4ngzhen/ node-adon-demo (github.com), which is convenient to complete the rapid construction of the environment in the future.