1. Preparation Software
windows7 or later
-
C:\Users\macrored\Desktop>python --version Python 3.7.7
-
C:\Users\macrored\Desktop>node -v v12.16.1
2. Examples
Create a new folder
package.json
{ "name": "test-cpp-module", "version": "0.1.0", "private": true, "gypfile": true, "dependencies": { "node-addon-api": "^2.0.0" } }
binding.gyp
{ "targets": [ { "target_name": "democpp", "sources": [ "democpp.cc" ], "include_dirs": [ "<!@(node -p \"require('node-addon-api').include\")" ], "libraries": [ ], "dependencies": [ "<!(node -p \"require('node-addon-api').gyp\")" ], "cflags!": ["-fno-exceptions"], "cflags_cc!": ["-fno-exceptions"], "defines": ["NAPI_CPP_EXCEPTIONS"], "xcode_settings": { "GCC_ENABLE_CPP_EXCEPTIONS": "YES" } } ] }
democpp.cc
#include <napi.h> using namespace Napi; String Hello(const CallbackInfo& info) { return String::New(info.Env(), "world"); } Napi::Object Init(Env env, Object exports) { exports.Set("hello", Function::New(env, Hello)); return exports; } NODE_API_MODULE(addon, Init)
In the current folder to open the command line, maintaining smooth network operationnpm install
E:\WorkSpace\Code\node-addon-cplus>npm install
> [email protected] install E:\WorkSpace\Code\node-addon-cplus
> node-gyp rebuild
E:\WorkSpace\Code\node-addon-cplus>if not defined npm_config_node_gyp (node "D:\
Program Files\nodejs\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin\\.
.\..\node_modules\node-gyp\bin\node-gyp.js" rebuild ) else (node "D:\Program Fi
les\nodejs\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js" rebuild )
Building the projects in this solution one at a time. To enable parallel build,
please add the "/m" switch.
nothing.c
win_delay_load_hook.cc
nothing.vcxproj -> E:\WorkSpace\Code\node-addon-cplus\build\Release\\nothing.
lib
democpp.cc
win_delay_load_hook.cc
e:\workspace\code\node-addon-cplus\node_modules\node-addon-api\napi-inl.h(2141)
: warning C4530: C++ exception handler used, but unwind semantics are not enabl
ed. Specify /EHsc (compiling source file ..\democpp.cc) [E:\WorkSpace\Code\node
-addon-cplus\build\democpp.vcxproj]
Creating library E:\WorkSpace\Code\node-addon-cplus\build\Release\democpp.
lib and object E:\WorkSpace\Code\node-addon-cplus\build\Release\democpp.exp
democpp.vcxproj -> E:\WorkSpace\Code\node-addon-cplus\build\Release\\democpp.
node
npm notice created a lockfile as package-lock.json. You should commit this file.
added 1 package from 50 contributors and audited 1 package in 15.303s
found 0 vulnerabilities
E:\WorkSpace\Code\node-addon-cplus>
Smooth translation, then get in the output file .\build\Release\democpp.node
, the next step in the node
callhello()
E:\WorkSpace\Code\node-addon-cplus>node
Welcome to Node.js v12.16.1.
Type ".help" for more information.
> testapp=require('./build/Release/democpp.node')
{ hello: [Function] }
> testapp.hello()
'world'
>
To provide the above example source file link
Reference article
[1] simple to use call nodejs c ++ (c ++ mixed programming and the js)