Last active
August 1, 2022 20:17
-
-
Save Heath123/00c170e66685f5c6c8717b11028bcb55 to your computer and use it in GitHub Desktop.
Copy/pastable files from https://medium.com/jspoint/a-simple-guide-to-load-c-c-code-into-node-js-javascript-applications-3fcccf54fd32
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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