Creating a calculator
Of course one would never bother to write an add-on to simply echo back strings. It is more likely that you will want to expose an API or interface to your Node programs. Let's create a simple calculator, with two methods: add
and subtract
. In this example, we will demonstrate how to pass arguments from JavaScript to methods within an add-on, and to send any results back.
The complete code for this example will be found in your code bundle. The meat of the program can be seen in this snippet, where we define an interface for our two methods, each one expect to receive two numbers as arguments:
#include <node.h> #include <v8.h> using namespace v8; Handle<Value> Add(const Arguments& args) { HandleScope scope; if(args.Length() < 2) { ThrowException(Exception::TypeError(String::New("Wrong number of arguments"))); return scope.Close(Undefined()); } if(!args[0]->IsNumber() || !args[1]->IsNumber()) { ThrowException...