4

Can someone explain the difference between the one-argument form and the two-argument form of Init when creating a c++ node.js addon?

void Init(Local<Object> exports) {}
void Init(Local<Object> exports, Local<Object> module) {}
ZachB
  • 13,051
  • 4
  • 61
  • 89
nick
  • 43
  • 3

1 Answers1

0

In general you could always use the second method template, but exports or module provide different options.

Using the following example:

void Init(Local<Object> exports) {
  NODE_SET_METHOD(exports, "test", MyTest);
}

will add the function test as a "function property" on your exports object.

So you could use the following JS code and it would, for example, print it out to the stdout using the test function from your exports object:

const test = require('./path/to/node/addon/addon.node');
test.test('my message');

On the other hand:

void Init(Local<Object> exports, Local<Object> module) {
  NODE_SET_METHOD(module, "exports", MyDummyCallback);
}

Provides you with the full module (module) and allows you to override your exports. You could call something like this from JS:

const test = require('./path/to/node/addon/addon.node');
test('test');

Will print your test message to the tty using the overridden module.

r0-
  • 2,388
  • 1
  • 24
  • 29