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

exports = myfunc;

当 nodejs 插件高于类型时,我可以将其用作...

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

如何在 C++ 中制作这种类型的插件?

4

1 回答 1

2

您可以通过直接设置来设置myfuncexports对象module.exports

function myfunc() {
}

module.exports = myfunc;

Modulesexports文档涵盖了和之间的区别module.exports

请注意,这exportsmodule.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-gyp它的依赖项和一个binding.gyp.

并且,请注意,第一个参数 forNODE_MODULE()应该"target_name"binding.gyp.

然后:

node-gyp rebuild
于 2013-06-28T08:06:08.043 回答