我可以将nodejs插件替换为“exports”对象吗?

时间:2013-06-28 06:03:20

标签: node.js

function myfunc() {
    // some codes...
}

exports = myfunc;

当nodejs addon高于type时,我可以将它用作...

var myfunc = require("./myfunc");
myfunc();

如何在c ++中创建这种类型的插件?

1 个答案:

答案 0 :(得分:2)

您可以通过直接设置module.exportsmyfunc设置为exports对象:

function myfunc() {
}

module.exports = myfunc;

Modules文档介绍了exportsmodule.exports之间的区别:

  

请注意,exports是对module.exports的引用,使其合适   仅用于扩充。如果要导出单个项目,例如   构造函数,您将直接使用module.exports

function MyConstructor (opts) {
  //...
}

// BROKEN: Does not modify exports
exports = MyConstructor;

// exports the constructor properly
module.exports = MyConstructor;

至于它是C++ Addon,一个粗略的例子是:

#include <node.h>

using namespace v8;

Handle<Value> MyFunc(const Arguments& args) {
  HandleScope scope;
  return scope.Close(Undefined());
}

void Init(Handle<Object> exports, Handle<Object> module) {
    module->Set(
        String::NewSymbol("exports"),
        FunctionTemplate::New(MyFunc)->GetFunction()
    );
}

NODE_MODULE(target_name, Init);

要构建它,您需要node-gypits dependenciesbinding.gyp

并且请注意,NODE_MODULE()的第一个参数应与"target_name"binding.gyp的值匹配。

然后:

node-gyp rebuild