node.jsnode.js-addon

How to mix Native Addon and Modules?


I developed a wrapper for a C++ library using node-addon-api. I'd like to export some node functions with those C++ functions.

Some functions can be coded in Javascript and don't require to be coded in C++.

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

How can we mix napi and nodeJs functions?


Solution

  • It's no problem to mix "native" functions and pure JS functions.

    Assuming you have an index.js in your project which serves as your main file

    package.json

    {
      "name": "mixedModule",
      "version": "1.0.0",
      "description": "A mixture of functions created via C++ or JS",
      "main": "index.js",
      "typings": "index.d.ts",
      "scripts": {
      ...
      }
    }
    

    you are free to decide which functions you want to (re-)export:

    const nativeModule = require("bindings")("myModule.node");
    
    function jsFunction() {
        ...
    }
    
    module.exports = {
      nativeFunction: nativeModule.nativeFunction,
      jsFunction
    }