nick nick - 4 months ago 15
Node.js Question

C++ node.js Addons - Explanation of parameters in Init()

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) {}


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');

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