Created
June 27, 2019 17:02
-
-
Save gabrielschulhof/fcfdf47703f9ee21a7eebbc1600c49c4 to your computer and use it in GitHub Desktop.
Send modules to native
This file contains hidden or 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 addon = require('bindings')('addon'); | |
addon.receiveModule('fs', require('fs')); | |
addon.receiveModule('crypto', require('crypto')); | |
console.log(addon.sendModule('fs') === require('fs')); | |
console.log(addon.sendModule('crypto') === require('crypto')); |
This file contains hidden or 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 <unordered_map> | |
using Napi::Error; | |
typedef struct { | |
std::unordered_map<std::string, Napi::ObjectReference> modules; | |
} AddonData; | |
void ReceiveModule(const Napi::CallbackInfo& info) { | |
AddonData* addon_data = static_cast<AddonData*>(info.Data()); | |
std::string name = info[0].As<Napi::String>(); | |
addon_data->modules[name] = Napi::Persistent(info[1].As<Napi::Object>()); | |
} | |
Napi::Value SendModule(const Napi::CallbackInfo& info) { | |
AddonData* addon_data = static_cast<AddonData*>(info.Data()); | |
std::string name = info[0].As<Napi::String>(); | |
return addon_data->modules[name].Value(); | |
} | |
static void DeleteAddonData(napi_env env, void* data, void* hint) { | |
(void) env; | |
(void) hint; | |
delete static_cast<AddonData*>(data); | |
} | |
Napi::Object Init(Napi::Env env, Napi::Object exports) { | |
AddonData* addon_data = new AddonData; | |
NAPI_THROW_IF_FAILED(env, | |
napi_wrap(env, exports, addon_data, DeleteAddonData, nullptr, nullptr), | |
exports); | |
exports["receiveModule"] = | |
Napi::Function::New(env, ReceiveModule, "receiveModule", addon_data); | |
exports["sendModule"] = | |
Napi::Function::New(env, SendModule, "sendModule", addon_data); | |
return exports; | |
} | |
NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init) |
In general, what can be done in JS should be done in JS. It's much faster, and a lot simpler. Do in C++ only what cannot be done without using C++.
... if I understood your question correctly.
Okay.Thank you :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No, I am asking if I can this approach of using js in N-API to protect the source code.