Search code examples
c++node.jsv8

how a node.js add-on check Arguments types


I use node.js for a while, now I need write an add-on, but I am a newb of c++.

in node.js I can pass optional arguments to function, and check their types.

function hello(arg, options, callback){
  if(!callback){
    if(typeof options === 'function'){
       callback = options;
       options = {};
    }
  }
  console.log(typeof arg);
}

But in an addon.

Handle<Value> hello(const Arguments &args) {
    HandleScope scope;
    printf("%d\n", args.Length());
    // how to check type of args[i]
    return String::New("world");
}

Solution

  • You should look over the API in http://v8.googlecode.com/svn/trunk/include/v8.h. Most of the functions you are interested are on the Value class. There is documentation online here, http://bespin.cz/~ondras/html/classv8_1_1Value.html but that looks like just some random person's uploaded version of the docs. Not sure if they are online somewhere else.

    Something like this should do about the same thing as your JS snippet.

    Handle<Value> hello(const Arguments &args) {
      HandleScope scope;
      Local<Value> arg(args[0]);
      Local<Value> options(args[1]);
      Local<Value> callback(args[2]);
    
      if (callback.equals(False())) {
        if (options->IsFunction()) {
          callback = options;
          options = Object::New();
        }
      }
    
      // ...
    }