V8: console.log实现

7

我在我的C++应用程序中使用V8,并且希望添加console.log()。有没有一些好的标准实现可以使用?

目前,我有自己的虚拟实现,但它相当不完整。

1个回答

7

我刚在Node.js的实现中发现了这个:

https://github.com/joyent/node/blob/master/lib/console.js https://github.com/joyent/node/blob/master/lib/util.js

当然,您需要采用此代码。它使用了Nodejs全局对象process及其stdoutstderr对象。以下是一些示例C++代码来创建这样的文件对象:

static void js_file_write(const v8::FunctionCallbackInfo<v8::Value>& info) {
    int fd = (int) info.Data().As<External>()->Value();
    auto isolate = Isolate::GetCurrent();
    if( info.Length() != 1) {
        isolate->ThrowException(
            v8::Exception::TypeError(jsStr("js_file_write: expects exactly 1 arg")));
        return;
    }
    if( !info[0]->IsString() ) {
        isolate->ThrowException(
            v8::Exception::TypeError(jsStr("js_file_write: expects a string")));
        return;
    }
    std::string s = jsObjToString(info[0], false, "");
    size_t c = 0;
    while(c < s.size()) {
        int ret = write(fd, &s[c], (unsigned int) (s.size() - c));
        if(ret < 0) {
            isolate->ThrowException(
                v8::Exception::Error(jsStr("js_file_write: write(" + to_string(fd) + ") error " + to_string(errno) + ": " + strerror(errno))));
            errno = 0;
            return;
        }
        c += ret;
    }
}


static Local<Object> makeFileObj(int fd) {
    auto isolate = Isolate::GetCurrent();
    Handle<External> selfRef = External::New(isolate, (void*) fd);
    auto obj = Object::New(isolate);
    obj->Set(jsStr("write"),
        FunctionTemplate::New(isolate, js_file_write, selfRef)->GetFunction());
    return obj;
}

static Local<Object> makeProcessObj() {
    auto obj = Object::New(Isolate::GetCurrent());
    obj->Set(jsStr("stdout"), makeFileObj(STDOUT_FILENO));
    obj->Set(jsStr("stderr"), makeFileObj(STDERR_FILENO));
    return obj;
}

jsStrjsObjToString 是非常经典的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接