Sunday 28 May 2017

nodejs c++ addon -- unable to node-gyp build using nan module

I am learning how to build C/C++ addons for nodejs.

I could successfully node-gyp configure, node-gyp build and run node index.js on a simple hellow world program. So, my basic setup is working. The below code (copy-paste from official nodejs documentation) is the working version of my C++ code.

//hello.cc
//#include <node.h>
//#include <nan.h>
#include "./node_modules/nan/nan.h"
#include <iostream> 
using namespace v8;

namespace demo {
  using v8::FunctionCallbackInfo;
  using v8::Isolate;
  using v8::Local;
  using v8::Object;
  using v8::String;
  using v8::Value;

  void Method (const FunctionCallbackInfo<Value>& args) {
    Isolate* isolate = args.GetIsolate();
    std::cout << "Executing some stupid func..." << std::endl;    
    args.GetReturnValue().Set(String::NewFromUtf8(isolate, "world"));
  }

  void init(Local<Object> exports) {
    NODE_SET_METHOD(exports, "hello", Method);
  }

  NODE_MODULE(addon, init)
} // namespace demo

However, when I use Nan module, and the version of code documented in the nan site, I get compilation errors indicating NanScope is not declared in this scope.

//hello.cc
#include "./node_modules/nan/nan.h"
#include <iostream> 
using namespace v8;

  NAN_METHOD(Method) {
          Nan::NanScope();
    NanReturnValue(String::New("world"));
  }

  void init(Handle<Object> exports) {
    exports->Set(NanSymbol("hello"), 
        FunctionTemplate::New(Method)->GetFunction());
  }

  NODE_MODULE(hello, init)

Part of the error output...

make: Entering directory '/home/rvnath/projects/comviva/node-addons/hello-world/build'
  CXX(target) Release/obj.target/addon/hello1.o
../hello1.cc: In function ‘Nan::NAN_METHOD_RETURN_TYPE Method(Nan::NAN_METHOD_ARGS_TYPE)’:
../hello1.cc:7:14: error: ‘NanScope’ was not declared in this scope
     NanScope();
              ^

After a bit of googling around, a few sites pointed out that we should be using Nan::Scope, and that the Nan documentation was out-of-date. I tried the change but it still didn't work. It gives an error saying "Scope is not a member of Nan".

I am unable to find, how to use the Nan version correctly. Any help here will be highly appreciated.



via Mupparthy Ravindranath

No comments:

Post a Comment