3

When programming a C++ Node.JS Addon, what is the equivalent of require('./someModule') so that a Module can be loaded for use within a compiled Addon?

I have found this method:

Handle<String> source = 
    String::New("NameOfLibrary.register(require('./someModule'))");
Handle<Script> script = 
    Script::Compile(source);
script->Run();

which if used in conjunction with what I asked here would work nicely, but I was wondering if there was a more native way.

2
  • You mean C++ I assume? Commented Jul 3, 2013 at 15:44
  • @loganfsmyth Yes, sorry Commented Jul 3, 2013 at 15:44

1 Answer 1

7

You should be able to access the standard module require function in your initialization function. Generally I'd just call it from there since lazy calls to require aren't a good idea since they are synchronous.

static void init (Handle<Object> target, Handle<Object> module) {
    HandleScope scope;
    Local<Function> require = Local<Function>::Cast(
        module->Get(String::NewSymbol("require")));

    Local<Value> args[] = {
        String::New("./someModule")
    };
    Local<Value> someModule = require->Call(module, 1, args);

    // Do whatever with the module
}


NODE_MODULE(module_file_name, init);
Sign up to request clarification or add additional context in comments.

1 Comment

Is there a way to do this using Napi? In Init(Napi::Env env, Napi::Object exports)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.