Before you start, make sure you've got all the necessary prerequisites and tools installed, and read Anatomy of a Node-API project to understand the common layout and configuration files shared by all node-addon-api projects.
This tutorial uses node-addon-api at the C++ wrapper level.
The quickest way to get a working project is to copy the Hello World example from the node-addon-examples repository:
git clone https://github.com/nodejs/node-addon-examples.git
cp -r node-addon-examples/src/1-getting-started/a-first-project/node-addon-api hello-world
cd hello-world
npm installAlternatively, set up the project manually:
mkdir hello-world
cd hello-world
npm init -y
npm install node-addon-apiThen create the source files described below. Once the project is set up, verify everything works:
npm testhello_world.cc is perhaps the simplest useful Node-API file you can write.
The file defines a C++ Method function that takes a single Napi::CallbackInfo& argument. This info object provides access to the JavaScript environment, including any arguments passed in from JavaScript.
infobehaves like an array of JavaScript arguments.
Method uses info to obtain a Napi::Env, then creates and returns a Napi::String with the value "world".
The Init function registers the single export from this module: the name "HelloWorld" maps to the Method function.
The NODE_API_MODULE macro at the bottom ensures Init is called when the module is loaded.
binding.js loads the compiled binary and re-exports its contents. The sole export from the binary is the HelloWorld function.
test_binding.js uses require to load the HelloWorld function from binding.js. The testBasic function calls it and verifies the result.
This project demonstrates a minimal Node-API module that exports a single function. Some things to try next:
- Run
test_binding.jsin your debugger. Step through the code and observe what visibility you have into the JavaScript object created by the C++ code. - Modify
test_binding.jsto require the compiled binary directly instead of going throughbinding.js. Step through in the debugger and note the difference. - Modify
hello_world.ccto read arguments passed from JavaScript. Thenode-addon-apiexamples are a good reference.