Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return JSON content in Node.js Addon

Tags:

c++

node.js

I'm making a Node.js extension, and I would like to return a json format object, instead of a json-formatted string.

#include <node.h>
#include <node_object_wrap.h>
using namespace v8;

void ListDevices(const FunctionCallbackInfo<Value>& args) {
    Isolate* isolate = Isolate::GetCurrent();
    HandleScope scope(isolate);

    std::string json = "[\"test\", \"test2\"]";
    args.GetReturnValue().Set(String::NewFromUtf8(isolate, json.c_str()));
}

void InitAll(Handle<Object> exports) {
    NODE_SET_METHOD(exports, "listDevices", ListDevices);
}

NODE_MODULE(addon, InitAll)

How can it be done ?

var addon = require("./ADDON");

var jsonvar = JSON.parse(addon.listDevices());
console.log(jsonvar);

Actually, in this part, I would like to remove the JSON.parse

By the way, is it me, or it is really difficult to find documentation ? I tried on google, but a lot of content was out of date, and in v8.h, interesting functions weren't documented.

Thank you ;)

like image 854
npielawski Avatar asked Oct 01 '22 14:10

npielawski


2 Answers

If you want to return a JS object or array, see the node addon docs (disregard the older v8 syntax since you are using node v0.11.x). Instead of creating a plain Object as in the linked example, use an Array instead.

like image 134
mscdex Avatar answered Oct 14 '22 22:10

mscdex


This should do it (node 0.12+):

void ListDevices(const FunctionCallbackInfo<Value>& args) {
    Isolate* isolate = args.GetIsolate();

    // create a new object on the v8 heap (json object)
    Local<Object> obj = Object::New(isolate);

    // set field "hello" with string "Why hello there." in that object
    obj->Set(String::NewFromUtf8(isolate, "hello"), String::NewFromUtf8(isolate, "Why hello there."));

    // return object
    args.GetReturnValue().Set(obj);
}

In short, your code is returning a string String::NewFromUtf8(isolate, ...) instead of an object Object::New(isolate).

like image 27
basickarl Avatar answered Oct 15 '22 00:10

basickarl