编写ASYNC CPP nodejs(0.5.3+)模块

时间:2011-10-21 14:08:54

标签: javascript c++ node.js

我正在寻找一种使用当前版本(0.5.9)为NodeJs构建c ++模块的方法。 通过使用以下教程并从节点node_file.cc中抽象,我能够自己为节点0.5.3构建一个模块。

但是对于节点0.5.4,一些API必须已经改变,因为我不再能够使用eio_ *来扭曲函数了。

查看node_file.cc我发现eio_ *包装被新的ReqWrap类替换。

此宏中的示例:https://gist.github.com/1303926

不,我不知道编写异步扩展的最佳方法是什么?

1 个答案:

答案 0 :(得分:15)

基本上看加密节点模块解决了我的问题,这个模块没有像文件模块这样的宏。我想出了一个简单的异步模块来计算两个整数的总和:

#include <v8.h>
#include <node.h>
#include <stdlib.h>
#include <errno.h>

using namespace node;
using namespace v8;

struct Test_req
{
    ssize_t result;
    ssize_t int1;
    ssize_t int2;
    Persistent<Function> callback;
};

void TestWorker(uv_work_t* req)
{
    Test_req* request = (Test_req*)req->data;
    request->result = request->int1 + request->int2;
}

void TestAfter(uv_work_t* req)
{
    HandleScope scope;

    Test_req* request = (Test_req*)req->data;
    delete req;

    Handle<Value> argv[2];

        // XXX: Error handling
    argv[0] = Undefined();
    argv[1] = Integer::New(request->result);

    TryCatch try_catch;

    request->callback->Call(Context::GetCurrent()->Global(), 2, argv);

    if (try_catch.HasCaught()) 
    {
        FatalException(try_catch);
    }

    request->callback.Dispose();

    delete request;
}


static Handle<Value> Test(const Arguments& args)
{

    HandleScope scope;

    if ( args.Length() < 3 || !args[0]->IsNumber() || !args[1]->IsNumber() )
    {
        return ThrowException(Exception::TypeError(String::New("Bad argument")));
    }

    ssize_t int1 ( args[0]->Int32Value() );
    ssize_t int2 ( args[1]->Int32Value() );

    if ( args[2]->IsFunction() )
    {
        Local<Function> callback = Local<Function>::Cast(args[2]);

        Test_req* request = new Test_req;
        request->callback = Persistent<Function>::New(callback);

        request->int1 = int1;
        request->int2 = int2;

        uv_work_t* req = new uv_work_t();
        req->data = request;

        uv_queue_work(uv_default_loop(), req, TestWorker, TestAfter);
    }
    else
    {
        return ThrowException(Exception::TypeError(String::New("Callback missing")));
    }

    return Undefined();
}

extern "C"
{
    static void init(Handle<Object> target)
    {
        HandleScope scope;
    }
}
NODE_MODULE(node_AsyncTest, init);

在节点端,您可以像这样调用模块:

var foo = process.binding('AsyncTest');

foo.Test(1,2,function(err,data){
  console.log(err,data);
});

结果:

undefined 3

希望这有用;)

Ps:由于Windows下缺少节点编译扩展。我使用Visual Studio构建解决方案直接将其构建到节点窗口的核心。