admin管理员组文章数量:1307583
I'm using V8 in my C++ app and I would like to add console.log()
. Is there some good standard implementation I can use?
Currently, I have my own dummy implementation but it's quite inplete.
I'm using V8 in my C++ app and I would like to add console.log()
. Is there some good standard implementation I can use?
Currently, I have my own dummy implementation but it's quite inplete.
Share Improve this question asked Mar 10, 2014 at 11:07 AlbertAlbert 68.4k68 gold badges252 silver badges403 bronze badges1 Answer
Reset to default 7I just found this implementation from Node.js:
https://github./joyent/node/blob/master/lib/console.js https://github./joyent/node/blob/master/lib/util.js
Of course you need to adopt this code. It uses the Nodejs global object process
and its stdout
and stderr
objects. Here is some sample C++ code to create such file objects:
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;
}
jsStr
and jsObjToString
are quite canonical.
本文标签: javascriptV8 consolelog implementationStack Overflow
版权声明:本文标题:javascript - V8: console.log implementation - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741840415a2400466.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论