Create Hello.cc file
# include <node_api.h>
namespace demo {
napi_value Method ( napi_env env, napi_callback_info args) {
napi_value greeting;
napi_status status;
status = napi_create_string_utf8 ( env, "world" , NAPI_AUTO_LENGTH, & greeting) ;
if ( status != napi_ok) return nullptr;
return greeting;
}
napi_value init ( napi_env env, napi_value exports) {
napi_status status;
napi_value fn;
status = napi_create_function ( env, nullptr, 0 , Method, nullptr, & fn) ;
if ( status != napi_ok) return nullptr;
status = napi_set_named_property ( env, exports, "hello" , fn) ;
if ( status != napi_ok) return nullptr;
return exports;
}
NAPI_MODULE ( NODE_GYP_MODULE_NAME, init)
}
Every node.js plugin must expose the initialization function of the following pattern:
void Initialize ( Local< Object> exports) ;
NODE_MODULE ( NODE_GYP_MODULE_NAME, Initialize)
module_name
Except for the different suffixes , the parameters .node
must match the final binary file name.
In the above example, the initialization function is init
to module_name
use a macro, which will ensure that the binary file name is passed as the first parameter when NODE_GYP_MODULE_NAME
the macro is used for compilation . node-gyp
NODE_MODULE
create binding.gyp
{
"targets" : [
{
"target_name" : "addon" ,
"sources" : [ "hello.cc" ]
}
]
}
This file is in json format and is node-gyp
used by tools to compile our plugin.
compile plugin
node-gyp configure build
Execute and compile our plugin in our project directory .
After the compilation is complete, ./build/Release
the binary file of our plug-in will be generated under the directory addon.node
.
test
Write the test file as follows
const addon = require ( './build/Release/addon' ) ;
console. log ( addon. hello ( ) ) ;
Execute the test file node hello.js
and it will be printed world
.
full code here