Pergunta

I'm transforming a parser for v8 in NodeJS. Currently I have the following structure

struct Node {
    short tag;
    std::string data;

    Node(std::string input, short tagId) {
        tag = tagId;
        data = input;
    }
}; 

std::vector<Node> elems;

And I'm populating the vector from loop like this:

 elems.push_back(Node(STRING, 3));

My goal is return a javascript object like this:

 [ 
   { tag: 2, data: "asdsad" },
   { tag: 2, data: "asdsad" },
   { tag: 2, data: "asdsad" }
 ]

But since the V8 documentation is crappy, I couldn't figure out how to do it. My best shot was to make

 Local<Value> data[2] = {
    Local<Value>::New(Integer::New(2)),
    String::New("test")
};

but I can't figure out how to make it an array and return it.

I'm using this example as template.

Foi útil?

Solução

Here's what you might try (node v0.10.x):

// in globals
static Persistent<String> data_symbol;
static Persistent<String> tag_symbol;


// in addon initialization function
data_symbol = NODE_PSYMBOL("data");
tag_symbol = NODE_PSYMBOL("tag");



// in some function somewhere
HandleScope scope;
Local<Array> nodes = Array::New();
for (unsigned int i = 0; i < elems.length; ++i) {
  HandleScope scope;
  Local<Object> node_obj = Object::New();
  node_obj->Set(data_symbol, String::New(elems[i].data.c_str()));
  node_obj->Set(tag_symbol, Integer::New(elems[i].tag));
  nodes->Set(i, node_obj);
}
return scope.Close(nodes);

Outras dicas

I was looking for a solution for Node 5, and it seems mscdex's answer is outdated now. Hope this helps someone.

HandleScope scope(isolate);
Local<Array> nodes = Array::New(isolate);
for (unsigned int i = 0; i < elems.length; ++i) {
  HandleScope scope(isolate);
  Local<Object> node = Object::New(isolate);
  node->Set(String::NewFromUtf8(isolate, "data"), String::New(isolate, elems[i].data.c_str()));
  node->Set(String::NewFromUtf8(isolate, "tag"), Integer::New(isolate, elems[i].tag));
  nodes->Set(i, node);
}

args.GetReturnValue().Set(nodes);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top