V8:console.log实现

时间:2014-03-10 11:07:13

标签: javascript v8

我在我的C ++应用程序中使用V8,我想添加console.log()。我可以使用一些好的标准实现吗?

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

1 个答案:

答案 0 :(得分:3)

我刚从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非常规范。