Skip to content

Instantly share code, notes, and snippets.

@gabrielschulhof
Created June 27, 2019 17:02
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gabrielschulhof/fcfdf47703f9ee21a7eebbc1600c49c4 to your computer and use it in GitHub Desktop.
Save gabrielschulhof/fcfdf47703f9ee21a7eebbc1600c49c4 to your computer and use it in GitHub Desktop.
Send modules to native
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'));
#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)
@gabrielschulhof
Copy link
Author

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++.

@gabrielschulhof
Copy link
Author

... if I understood your question correctly.

@sudhakar3697
Copy link

Okay.Thank you :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment