For native module basics, see:
For APIs, see:
For native module basics, see:
For APIs, see:
| # -*- 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) |