Recent Posts Toggle

[node.js] How to making node.js addon

1. create a C++ file.

2. create a file called binding.gyp which describes the configuration to build your module in a JSON-like format.

 

$ npm install -g node-gyp //node.js native addon build tool

$ node-gyp configure //generate the appropriate project build files for the current platform

$ node-gyp build

 

$node-gyp configure build

$node-gyp clean //Removes the build directory if it exists

boost addon test code

#include <node.h>
#include <v8.h>

#include <iostream>
#include <string>

#include <boost/random.hpp>

using namespace v8;
using namespace boost;

void Random(const FunctionCallbackInfo<Value>& args) { //random(iterator,min,max)
    Isolate* isolate = Isolate::GetCurrent();
    HandleScope scope(isolate);

    mt19937 gen;
    if(args[1]->NumberValue()<=args[2]->NumberValue()){
         uniform_int<> dst(args[1]->NumberValue(),args[2]->NumberValue());
         variate_generator<mt19937,uniform_int<> > rand(gen,dst);

         Local<String> val = String::NewFromUtf8(isolate, “Return : “);

         for(int i = 0; i != args[0]->NumberValue(); ++i){
             Local<Number> jmTest = Number::New(isolate, rand());
             val = String::Concat(val, String::NewFromUtf8(isolate, ” “));
             val = String::Concat(val, jmTest->ToString());
         }

        args.GetReturnValue().Set(val);

    }else{
         uniform_int<> dst(args[2]->NumberValue(),args[1]->NumberValue());
         variate_generator<mt19937,uniform_int<> > rand(gen,dst);

         Local<String> val = String::NewFromUtf8(isolate, “Return : “);

         for(int i = 0; i != args[0]->NumberValue(); ++i){
                 Local<Number> jmTest = Number::New(isolate, rand());
                 val = String::Concat(val, String::NewFromUtf8(isolate, ” “));
                 val = String::Concat(val, jmTest->ToString());
         }

         args.GetReturnValue().Set(val);
    }
}

void init(Handle<Object> exports) {
    NODE_SET_METHOD(exports, “random”, Random);
}

NODE_MODULE(boost, init)

binding.gyp file

{
    “targets”: [
    {
        “target_name”: “boost”,
        “sources”: [ “boost.cc” ],
        “include_dirs”: [
            “/usr/local/include/boost”,
        ],
        “libraries”: [
            “/usr/local/lib/libboost_random.dylib”
        ],
        “cflags_cc!”: [ “-fno-rtti”, “-fno-exceptions” ],
        “cflags!”: [ “-fno-exceptions” ],
        “conditions”: [
            [ ‘OS==”mac”‘, {
                “xcode_settings”: {
                    ‘OTHER_CPLUSPLUSFLAGS’ : [‘-std=c++11′,’-stdlib=libc++’, ‘-v’],
                    ‘OTHER_LDFLAGS’: [‘-stdlib=libc++’],
                    ‘MACOSX_DEPLOYMENT_TARGET’: ‘10.7’,
                    ‘GCC_ENABLE_CPP_EXCEPTIONS’: ‘YES’
                }
            }]
        ]
    }
    ]
}
ShutDown