问题。如何module.exports
在我的插件中添加功能化方法?
我想执行以下节点代码。
const hello = require('./build/Release/hello')
hello((msg) => { console.log(msg) }) // prints 'hello world'
console.log('hello', hello.hello()) // prints 'hello world'
console.log('3 + 5 =', hello.add(3, 5)) // prints '3 + 5 = 8'
以下是核心 C++ 代码。
#include <node.h>
namespace hello {
using v8::Exception;
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Null;
using v8::Number;
using v8::Object;
using v8::String;
using v8::Value;
void hello(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
args.GetReturnValue().Set(String::NewFromUtf8(isolate, "world"));
}
void add(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
if (args.Length() < 2) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Wrong number of arguments")));
return;
}
if (!args[0]->IsNumber() || !args[1]->IsNumber()) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Wrong arguments")));
return;
}
double value = args[0]->NumberValue() + args[1]->NumberValue();
Local<Number> num = Number::New(isolate, value);
args.GetReturnValue().Set(num);
}
void runCallback(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
Local<Function> cb = Local<Function>::Cast(args[0]);
const unsigned int argc = 1;
Local<Value> argv[argc] = { String::NewFromUtf8(isolate, "hello world") };
cb->Call(Null(isolate), argc, argv);
}
void init(Local<Object> exports, Local<Object> module) {
// TODO: It doesn't seem correct code.
NODE_SET_METHOD(module, "exports", runCallback);
NODE_SET_METHOD(exports, "hello", hello);
NODE_SET_METHOD(exports, "add", add);
}
NODE_MODULE(hello, init);
}
但它会引发一些错误。
console.log('hello', hello.hello())
^
TypeError: hello.hello is not a function
at Object.<anonymous> (C:\Users\user\Desktop\hello\test.js:3:28)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Module.runMain (module.js:575:10)
at run (node.js:348:7)
at startup (node.js:140:9)
at node.js:463:3
如果我评论第 3 行,则会继续抛出相同的错误。
TypeError: hello.add is not a function
但是当我评论第 3 行和第 4 行时,它会打印“hello world”。
hello world