Last active
October 13, 2019 13:28
-
-
Save ghaiklor/ddd6c57e9f8cbae06d81 to your computer and use it in GitHub Desktop.
NodeJS method that returns JavaScript object from bindings
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
static void Binding(const FunctionCallbackInfo<Value>& args) { | |
Environment* env = Environment::GetCurrent(args); | |
Local<String> module = args[0]->ToString(env->isolate()); | |
node::Utf8Value module_v(env->isolate(), module); | |
Local<Object> cache = env->binding_cache_object(); | |
Local<Object> exports; | |
if (cache->Has(module)) { | |
exports = cache->Get(module)->ToObject(env->isolate()); | |
args.GetReturnValue().Set(exports); | |
return; | |
} | |
// Append a string to process.moduleLoadList | |
char buf[1024]; | |
snprintf(buf, sizeof(buf), "Binding %s", *module_v); | |
Local<Array> modules = env->module_load_list_array(); | |
uint32_t l = modules->Length(); | |
modules->Set(l, OneByteString(env->isolate(), buf)); | |
node_module* mod = get_builtin_module(*module_v); | |
if (mod != nullptr) { | |
exports = Object::New(env->isolate()); | |
// Internal bindings don't have a "module" object, only exports. | |
CHECK_EQ(mod->nm_register_func, nullptr); | |
CHECK_NE(mod->nm_context_register_func, nullptr); | |
Local<Value> unused = Undefined(env->isolate()); | |
mod->nm_context_register_func(exports, unused, | |
env->context(), mod->nm_priv); | |
cache->Set(module, exports); | |
} else if (!strcmp(*module_v, "constants")) { | |
exports = Object::New(env->isolate()); | |
DefineConstants(exports); | |
cache->Set(module, exports); | |
} else if (!strcmp(*module_v, "natives")) { | |
exports = Object::New(env->isolate()); | |
DefineJavaScript(env, exports); | |
cache->Set(module, exports); | |
} else { | |
char errmsg[1024]; | |
snprintf(errmsg, | |
sizeof(errmsg), | |
"No such module: %s", | |
*module_v); | |
return env->ThrowError(errmsg); | |
} | |
args.GetReturnValue().Set(exports); | |
} | |
env->SetMethod(process, "binding", Binding); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment