Skip to content

Instantly share code, notes, and snippets.

@Heath123
Last active August 1, 2022 20:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Heath123/00c170e66685f5c6c8717b11028bcb55 to your computer and use it in GitHub Desktop.
Save Heath123/00c170e66685f5c6c8717b11028bcb55 to your computer and use it in GitHub Desktop.
#include <napi.h>
#include <string>
#include "greeting.h"
// native C++ function that is assigned to `greetHello` property on `exports` object
Napi::String greetHello(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
// call `helloUser` function from `greeting.cpp` file
// WARNING: We are passing hardcoded `MIKE` value for now
std::string result = helloUser( "MIKE" );
// return new `Napi::String` value
return Napi::String::New(env, result);
}
// callback method when module is registered with Node.js
Napi::Object Init(Napi::Env env, Napi::Object exports) {
// set a key on `exports` object
exports.Set(
Napi::String::New(env, "greetHello"), // property name => "greetHello"
Napi::Function::New(env, greetHello) // property value => `greetHello` function
);
// return `exports` object (always)
return exports;
}
// register `greet` module which calls `Init` method
NODE_API_MODULE(greet, Init)
const greetModule = require( './build/Release/greet.node' );
// see properties on `exports` object
console.log( 'exports : ', greetModule );
console.log();
// execute `greetHello` function
console.log( 'greetModule.greetHello() : ', greetModule.greetHello() );
console.log();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment