0

I am trying to pass a string to a C++ add on in Node.js. I am using the Nan library as seems to be recommended. For the equivalent task with a number I do the following:

NAN_METHOD(funcName) {
    if (!info[0]->IsUint32()) {
        Nan::ThrowError("Argument must be an unsigned int 32");
    }
    v8::Local<v8::Context> ctxt = info.GetIsolate()->GetCurrentContext();

    uint32_t blocks;
    info[0]->Uint32Value(ctxt).To(&blocks);
}

after which I can work with the blocks variable. There doesn't seem to be any equivalent StringValue function. I have tried info[0]->ToString(ctxt) but this gives me a MaybeLocal which seems to be a null check around local. Once I convert to v8::Local<v8::String> I have no idea how to actually access the string value. I have also tried info[0]->Cast but this also does not work. Any help would be appreciated.

cershif
  • 154
  • 1
  • 13

1 Answers1

0

Do not forget that V8 stores internally all strings as UTF-16 unlike most other languages/frameworks which use UTF-8.

Here is a sample code:

  if (info.Length() < num + 1) {
    Nan::ThrowError(name " must be given");
    return;
  }
  if (!info[num]->IsString()) {
    Nan::ThrowTypeError(name " must be a string");                    
    return;
  }                                
  std::string var = (*Nan::Utf8String(info[num]));

You can check this which has many defines for decoding various values passed to a NaN C++ method from JS: https://github.com/mmomtchev/node-gdal-async/blob/983a5df62ceb85f8c1fb580d6d7d496f38db36cd/src/gdal_common.hpp#L429

mmomtchev
  • 2,497
  • 1
  • 8
  • 23