Skip to content
Sugar for your Node C++ addons
Find file
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.

Sugar for your Node C++ addons

Have you ever written a C/C++ addon for Node.JS?
If you have, you probably are tired of writing so much code for just having the skeleton of it.
Sure, the V8 syntax is very verbose and repetitive.

With V8U, that will change.

Enough talking, show me code!

Here we have a simple module which exposes one class Hello, with one method, world.
It takes one string as argument, and just returns it untouched.

class Hello : public ObjectWrap {
  //The constructor
  static Handle<Value> NewInstance(const Arguments& args) {
    if (!args.IsConstructCall())
      return ThrowException(Exception::Error(String::New("Not called as constructor!")));
    Hello* instance = new Hello;
    return args.This();

  //The world() method
  static Handle<Value> World(const Arguments& args) {
    if (args.Length() < 1)
      return ThrowException(Exception::RangeError(String::New("Not enough arguments!")));
    if (!args[0]->IsString())
      return ThrowException(Exception::TypeError(String::New("Arg must be a string!")));
    return scope.Close(args[0]);

extern "C" {
  static void initHello(Handle<Object> target) {
    Local<FunctionTemplate> protL = FunctionTemplate::New(Hello::NewInstance);
    Persistent<FunctionTemplate> prot = Persistent<FunctionTemplate>::New(protL);
    NODE_SET_PROTOTYPE_METHOD(prot, "world", Hello::World);
    target->Set(String::NewSymbol("Hello"), prot->GetFunction();
  NODE_MODULE(simpleaddon, initHello);

With V8U, things start to look better:

class Hello : public ObjectWrap {
  V8_CL_CTOR(Hello, 0) {
    inst = new Hello;
  } V8_CL_CTOR_END()

  V8_CL_CALLBACK(Hello, World, 1) {
    if (!args[0]->IsString())
      V8_THROW(TypeErr("Arg must be a string!"));
    return scope.Close(args[0]);
  } V8_WRAP_END()

NODE_DEF_TYPE(Hello, "Hello") {
  NODE_DEF_METHOD(Hello, World, "world");

} NODE_DEF_MAIN_END(simpleaddon)

And that's just scratching the surface of what V8U provides.
What's more, V8U cares about exception wrapping, persistent handles, and other things for you!

How to use

To use V8U, simply copy the HPP file into your project.
Then include it:

#include "v8u.hpp"
using namespace v8u;

Now, let the fun begin!

TODO: explain syntax and macros
For now, you can look at Robotskirt to see a usage example.

Something went wrong with that request. Please try again.