nodejs源码阅读和实践,模拟process传递过程
发布于 12 年前 作者 wangfei1204 6804 次浏览 最后一次编辑是 8 年前

最近在看nodejs的源码,一头雾水,然后看到了一位前辈的这个文章,让我找到了方向

[node.js源码研究—模块组织加载][1]

然后就自己实践写代码模拟process传递过程,实践后印象才深刻,把代码贴在这里,欢迎大家一起讨论读node源码的心得体会,node源码的资料现在好少

#include <v8.h>
#include <iostream>
using namespace v8;
using namespace std;

static Persistent<Object> process;


Handle<Value> print (const Arguments& args) {
    HandleScope scope;

    printf("In print\n");
    for (int i = 0; i< args.Length(); ++i) {
        cout << *String::Utf8Value (args[i]) << " ";
    }

    cout << endl;

    return Undefined ();
}

int main(int argc, char* argv[])
{
  HandleScope handle_scope;
  Persistent<Context> context = Context::New();
  Context::Scope context_scope(context);

  Local<FunctionTemplate> process_template = FunctionTemplate::New();
  process = Persistent<Object>::New(process_template->GetFunction()->NewInstance());
  process->Set(String::NewSymbol("version"), String::New("0.0.1"));
  process->Set(String::NewSymbol("log"), FunctionTemplate::New(print)->GetFunction());

  context->Global()->Set(String::New("log"), FunctionTemplate::New(print)->GetFunction());

  Local<String> str = String::New("(function(process){log(arguments.length, process.version); process.log('I', 'Love', 'Node');}) ");
  Local<Value> result1 = Script::Compile(str)->Run();
  Local<Function> f = Local<Function>::Cast(result1);
  Local<Value> args[1] = {Local<Value>::New(process)};
  f->Call(Context::GetCurrent()->Global(), 1, args);

  return 0;
}
2 回复

说下吧,可以这样给代码排版,先在输入区域粘贴代码,然后选中所有代码,然后按ctrl+k,这样代码就不会乱。

感谢!按照你的方法编辑好了

回到顶部