Skip to content

Commit 4b61522

Browse files
committed
test: add an "async-hello-world" native addon test
1 parent 055110d commit 4b61522

3 files changed

Lines changed: 80 additions & 0 deletions

File tree

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
#include <unistd.h>
2+
#include <node.h>
3+
#include <v8.h>
4+
#include <uv.h>
5+
6+
using namespace v8;
7+
using namespace node;
8+
9+
struct async_req {
10+
uv_work_t req;
11+
int input;
12+
int output;
13+
Persistent<Function> callback;
14+
};
15+
16+
void DoAsync (uv_work_t *r) {
17+
async_req *req = reinterpret_cast<async_req *>(r->data);
18+
sleep(1); // simulate CPU intensive process...
19+
req->output = req->input * 2;
20+
}
21+
22+
void AfterAsync (uv_work_t *r) {
23+
HandleScope scope;
24+
async_req *req = reinterpret_cast<async_req *>(r->data);
25+
26+
Handle<Value> argv[2] = { Null(), Integer::New(req->output) };
27+
28+
TryCatch try_catch;
29+
30+
req->callback->Call(Context::GetCurrent()->Global(), 2, argv);
31+
32+
// cleanup
33+
req->callback.Dispose();
34+
delete req;
35+
36+
if (try_catch.HasCaught()) {
37+
FatalException(try_catch);
38+
}
39+
}
40+
41+
Handle<Value> Method(const Arguments& args) {
42+
HandleScope scope;
43+
44+
async_req *req = new async_req;
45+
req->req.data = req;
46+
47+
req->input = args[0]->IntegerValue();
48+
req->output = 0;
49+
50+
Local<Function> callback = Local<Function>::Cast(args[1]);
51+
req->callback = Persistent<Function>::New(callback);
52+
53+
uv_queue_work(uv_default_loop(),
54+
&req->req,
55+
DoAsync,
56+
(uv_after_work_cb)AfterAsync);
57+
58+
return Undefined();
59+
}
60+
61+
void init(Handle<Object> exports, Handle<Object> module) {
62+
NODE_SET_METHOD(module, "exports", Method);
63+
}
64+
65+
NODE_MODULE(binding, init);
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
'targets': [
3+
{
4+
'target_name': 'binding',
5+
'sources': [ 'binding.cc' ]
6+
}
7+
]
8+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
var assert = require('assert');
2+
var binding = require('./build/Release/binding');
3+
binding(5, function (err, val) {
4+
assert.equal(null, err);
5+
assert.equal(10, val);
6+
console.error('done :)');
7+
});

0 commit comments

Comments
 (0)