Skip to content

Instantly share code, notes, and snippets.

@maksimr
Last active June 8, 2023 08:07
Show Gist options
  • Select an option

  • Save maksimr/b9d88373fbd915c4ed8091df6aed7ad3 to your computer and use it in GitHub Desktop.

Select an option

Save maksimr/b9d88373fbd915c4ed8091df6aed7ad3 to your computer and use it in GitHub Desktop.
πŸ“ Getting started with C++ extension for Node.js

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

node-addon-api and node-api-headers contain the C++ headers required to build the extension

echo.h

cat > src/echo.h <<EOF
#include <string>
std::string echo(std::string value);
EOF

echo.cpp

cat > src/echo.cpp <<EOF
#include <string>
#include "echo.h"
std::string echo(std::string value)
{
  return value;
}
EOF

index.cpp - is the entry point for the extension

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

binding.gyp - is the build configuration file for the extension

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

Configure and build extension:

npx node-gyp configure build

index.js

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": [
    {
      ...
      "sources": [ "<!@(find src -name '*.cpp')"],
      ...
    }
  ]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment