πŸ“ Note: Getting started with C++ extension for Node.js

Maksim Ryzhikov
1 min readJun 7, 2023

https://nodejs.org/api/n-api.html#node-api

mk -p /tmp/echo/src
pushd /tmp/echo
npm init -y
npm install -S node-addon-api node-api-headers
touch src/index.cpp src/echo.h src/echo.cpp
cat > src/echo.h <<EOF
#include <string>
std::string echo(std::string value);
EOF
cat > src/echo.cpp <<EOF
#include <string>
#include "echo.h"
std::string echo(std::string value)
{
return value;
}
EOF
cat > src/index.cpp <<EOF
#include <napi.h>
#include <string>
#include "echo.h"

Napi::String echoMethod(const Napi::CallbackInfo &info)
{
Napi::Env env = info.Env();
std::string value = info[0].As<Napi::String>();
std::string result = echo(value);
return Napi::String::New(env, result);
}

Napi::Object Init(Napi::Env env, Napi::Object exports)
{
exports.Set(Napi::String::New(env, "echo"), Napi::Function::New(env, echoMethod));
return exports;
}

NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init)
EOF
cat > binding.gyp <<EOF
{
"targets": [
{
"target_name": "echo",
"sources": ["src/echo.cpp", "src/index.cc"],
"include_dirs": [
"<!@(node -p \"require('node-addon-api').include\")"
],
'defines': ['NAPI_DISABLE_CPP_EXCEPTIONS']
}
]
}
EOF
npx node-gyp configure build
cat > index.js <<EOF
const echo = require('./build/Release/echo.node');
console.log(echo.echo('Hello World'));
EOF
node index.js

Tips and tricks:

Auto expand sources:

{
"targets": [
{
"target_name": "echo",
"sources": [ "<!@(find src -name '*.cpp')"],
"include_dirs": [
"<!@(node -p \"require('node-addon-api').include\")"
],
'defines': ['NAPI_DISABLE_CPP_EXCEPTIONS']
}
]
}

--

--