Skip to content

Instantly share code, notes, and snippets.

@bellbind
Last active June 20, 2024 18:22
Show Gist options
  • Select an option

  • Save bellbind/b69c3aa266cffe43940c to your computer and use it in GitHub Desktop.

Select an option

Save bellbind/b69c3aa266cffe43940c to your computer and use it in GitHub Desktop.
[nodejs]Native module with libuv and v8::Promise on node-4
# -*- mode: python -*-
{
"targets": [
{
"include_dirs": ["<!(node -e \"require('nan')\")"],
"target_name": "TimerAndPromise",
"sources": [
"timer-and-promise.cc"
],
"conditions": [
["OS != 'win'",{
"cflags": ["-Wall", "-Wextra", "-pedantic"],
"cflags_cc": ["-std=c++14"],
}]
],
},
],
}
{
"name": "timer-and-promise",
"version": "0.1.0",
"description": "Native module example with libuv uv_timer and promise",
"license": "MIT",
"repository": "gist:",
"engine": {"node": ">=4.0.0"},
"main": "./build/Release/TimerAndPromise",
"dependencies": {
"nan": ">=2.0.0"
}
}
use strict";
let m = require(".");
m.wait(10).then((msg) => console.log(`OK: ${msg}`));
// build: npm install
#include <nan.h>
// callback for uv_timer
void timercb(uv_timer_t* handle) {
Nan::HandleScope scope;
auto persistent =
static_cast<v8::Persistent<v8::Promise::Resolver>*>(handle->data);
uv_timer_stop(handle);
uv_close(reinterpret_cast<uv_handle_t*>(handle),
[](uv_handle_t* handle) -> void {delete handle;});
auto resolver =
v8::Local<v8::Promise::Resolver>::New(v8::Isolate::GetCurrent(),
*persistent);
resolver->Resolve(Nan::New("invoked").ToLocalChecked());
persistent->Reset();
delete persistent;
}
// Promise returned function
NAN_METHOD(Wait) {
auto ms = Nan::To<unsigned>(info[0]).FromJust();
auto resolver = v8::Promise::Resolver::New(info.GetIsolate());
auto promise = resolver->GetPromise();
auto persistent = new v8::Persistent<v8::Promise::Resolver>();
persistent->Reset(info.GetIsolate(), resolver);
uv_timer_t* handle = new uv_timer_t;
handle->data = persistent;
uv_timer_init(uv_default_loop(), handle);
uv_timer_start(handle, timercb, ms, 0);
info.GetReturnValue().Set(promise);
}
NAN_MODULE_INIT(InitAll) {
Nan::Export(target, "wait", Wait);
}
NODE_MODULE(TimerAndPromise, InitAll)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment