如何在Node.js插件中返回JSON内容

How to return JSON content in Node.js Addon

本文关键字:返回 JSON 内容 插件 js Node      更新时间:2023-10-16

我正在做一个Node.js扩展,我想返回一个json格式的对象,而不是json格式的字符串。

#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)

怎么做呢?

var addon = require("./ADDON");
var jsonvar = JSON.parse(addon.listDevices());
console.log(jsonvar);

实际上,在这一部分中,我想删除JSON.parse

顺便问一下,是我的问题,还是真的很难找到文档?我在谷歌上尝试过,但是很多内容都过时了,而且在v8.h中,有趣的功能没有记录。

如果你想返回一个JS对象或数组,请参阅node插件文档(因为你使用的是node v0.11.x,所以请忽略旧的v8语法)。与在链接示例中创建普通对象不同,使用Array代替。

应该这样做(节点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);
}

简而言之,您的代码返回的是字符串String::NewFromUtf8(isolate, ...),而不是对象Object::New(isolate)

你不能那样做。JSON是一种序列化格式。它使用字符串来传递数据。您需要解析该字符串以形成JS对象。这个必须在某个时刻完成。

换句话说,没有"JSON格式的对象"这样的东西。你正在考虑的对象可能是Javascript对象,它不是字符串,当然也不是c++对象。字符串只表示对象,必须对其进行转换。