|
| 1 | +// addon.cc |
| 2 | +#include <node.h> |
| 3 | + |
| 4 | +namespace demo { |
| 5 | + |
| 6 | +using v8::Exception; |
| 7 | +using v8::FunctionCallbackInfo; |
| 8 | +using v8::Isolate; |
| 9 | +using v8::Local; |
| 10 | +using v8::Number; |
| 11 | +using v8::Object; |
| 12 | +using v8::String; |
| 13 | +using v8::Value; |
| 14 | + |
| 15 | +// This is the implementation of the "add" method |
| 16 | +// Input arguments are passed using the |
| 17 | +// const FunctionCallbackInfo<Value>& args struct |
| 18 | +void Add(const FunctionCallbackInfo<Value>& args) { |
| 19 | + Isolate* isolate = args.GetIsolate(); |
| 20 | + |
| 21 | + // Check the number of arguments passed. |
| 22 | + if (args.Length() < 2) { |
| 23 | + // Throw an Error that is passed back to JavaScript |
| 24 | + isolate->ThrowException(Exception::TypeError( |
| 25 | + String::NewFromUtf8(isolate, "Wrong number of arguments"))); |
| 26 | + return; |
| 27 | + } |
| 28 | + |
| 29 | + // Check the argument types |
| 30 | + if (!args[0]->IsNumber() || !args[1]->IsNumber()) { |
| 31 | + isolate->ThrowException(Exception::TypeError( |
| 32 | + String::NewFromUtf8(isolate, "Wrong arguments"))); |
| 33 | + return; |
| 34 | + } |
| 35 | + |
| 36 | + // Perform the operation |
| 37 | + double value = args[0]->NumberValue() + args[1]->NumberValue(); |
| 38 | + Local<Number> num = Number::New(isolate, value); |
| 39 | + |
| 40 | + // Set the return value (using the passed in |
| 41 | + // FunctionCallbackInfo<Value>&) |
| 42 | + args.GetReturnValue().Set(num); |
| 43 | +} |
| 44 | + |
| 45 | +void Init(Local<Object> exports) { |
| 46 | + NODE_SET_METHOD(exports, "add", Add); |
| 47 | +} |
| 48 | + |
| 49 | +NODE_MODULE(addon, Init) |
| 50 | + |
| 51 | +} // namespace demo |
0 commit comments