Domanda

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.

È stato utile?

Soluzione

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);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top