Frage

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.

War es hilfreich?

Lösung

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);
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top