You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

705 lines
26 KiB

  1. Native Abstractions for Node.js
  2. ===============================
  3. **A header file filled with macro and utility goodness for making addon development for Node.js easier across versions 0.8, 0.10 and 0.11, and eventually 0.12.**
  4. ***Current version: 0.3.2*** *(See [nan.h](https://github.com/rvagg/nan/blob/master/nan.h) for changelog)*
  5. [![NPM](https://nodei.co/npm/nan.png?downloads=true&stars=true)](https://nodei.co/npm/nan/) [![NPM](https://nodei.co/npm-dl/nan.png?months=6)](https://nodei.co/npm/nan/)
  6. Thanks to the crazy changes in V8 (and some in Node core), keeping native addons compiling happily across versions, particularly 0.10 to 0.11/0.12, is a minor nightmare. The goal of this project is to store all logic necessary to develop native Node.js addons without having to inspect `NODE_MODULE_VERSION` and get yourself into a macro-tangle.
  7. This project also contains some helper utilities that make addon development a bit more pleasant.
  8. * **[Usage](#usage)**
  9. * **[Example](#example)**
  10. * **[API](#api)**
  11. <a name="usage"></a>
  12. ## Usage
  13. Simply add **NAN** as a dependency in the *package.json* of your Node addon:
  14. ```js
  15. "dependencies": {
  16. ...
  17. "nan" : "~0.3.1"
  18. ...
  19. }
  20. ```
  21. Pull in the path to **NAN** in your *binding.gyp* so that you can use `#include "nan.h"` in your *.cpp*:
  22. ```js
  23. "include_dirs" : [
  24. ...
  25. "<!(node -p -e \"require('path').dirname(require.resolve('nan'))\")"
  26. ...
  27. ]
  28. ```
  29. This works like a `-I<path-to-NAN>` when compiling your addon.
  30. <a name="example"></a>
  31. ## Example
  32. See **[LevelDOWN](https://github.com/rvagg/node-leveldown/pull/48)** for a full example of **NAN** in use.
  33. For a simpler example, see the **[async pi estimation example](https://github.com/rvagg/nan/tree/master/examples/async_pi_estimate)** in the examples directory for full code and an explanation of what this Monte Carlo Pi estimation example does. Below are just some parts of the full example that illustrate the use of **NAN**.
  34. Compare to the current 0.10 version of this example, found in the [node-addon-examples](https://github.com/rvagg/node-addon-examples/tree/master/9_async_work) repository and also a 0.11 version of the same found [here](https://github.com/kkoopa/node-addon-examples/tree/5c01f58fc993377a567812597e54a83af69686d7/9_async_work).
  35. Note that there is no embedded version sniffing going on here and also the async work is made much simpler, see below for details on the `NanAsyncWorker` class.
  36. ```c++
  37. // addon.cc
  38. #include <node.h>
  39. #include "nan.h"
  40. // ...
  41. using namespace v8;
  42. void InitAll(Handle<Object> exports) {
  43. exports->Set(NanSymbol("calculateSync"),
  44. FunctionTemplate::New(CalculateSync)->GetFunction());
  45. exports->Set(NanSymbol("calculateAsync"),
  46. FunctionTemplate::New(CalculateAsync)->GetFunction());
  47. }
  48. NODE_MODULE(addon, InitAll)
  49. ```
  50. ```c++
  51. // sync.h
  52. #include <node.h>
  53. #include "nan.h"
  54. NAN_METHOD(CalculateSync);
  55. ```
  56. ```c++
  57. // sync.cc
  58. #include <node.h>
  59. #include "nan.h"
  60. #include "sync.h"
  61. // ...
  62. using namespace v8;
  63. // Simple synchronous access to the `Estimate()` function
  64. NAN_METHOD(CalculateSync) {
  65. NanScope();
  66. // expect a number as the first argument
  67. int points = args[0]->Uint32Value();
  68. double est = Estimate(points);
  69. NanReturnValue(Number::New(est));
  70. }
  71. ```
  72. ```c++
  73. // async.cc
  74. #include <node.h>
  75. #include "nan.h"
  76. #include "async.h"
  77. // ...
  78. using namespace v8;
  79. class PiWorker : public NanAsyncWorker {
  80. public:
  81. PiWorker(NanCallback *callback, int points)
  82. : NanAsyncWorker(callback), points(points) {}
  83. ~PiWorker() {}
  84. // Executed inside the worker-thread.
  85. // It is not safe to access V8, or V8 data structures
  86. // here, so everything we need for input and output
  87. // should go on `this`.
  88. void Execute () {
  89. estimate = Estimate(points);
  90. }
  91. // Executed when the async work is complete
  92. // this function will be run inside the main event loop
  93. // so it is safe to use V8 again
  94. void HandleOKCallback () {
  95. NanScope();
  96. Local<Value> argv[] = {
  97. Local<Value>::New(Null())
  98. , Number::New(estimate)
  99. };
  100. callback->Call(2, argv);
  101. };
  102. private:
  103. int points;
  104. double estimate;
  105. };
  106. // Asynchronous access to the `Estimate()` function
  107. NAN_METHOD(CalculateAsync) {
  108. NanScope();
  109. int points = args[0]->Uint32Value();
  110. NanCallback *callback = new NanCallback(args[1].As<Function>());
  111. NanAsyncQueueWorker(new PiWorker(callback, points));
  112. NanReturnUndefined();
  113. }
  114. ```
  115. <a name="api"></a>
  116. ## API
  117. * <a href="#api_nan_method"><b><code>NAN_METHOD</code></b></a>
  118. * <a href="#api_nan_getter"><b><code>NAN_GETTER</code></b></a>
  119. * <a href="#api_nan_setter"><b><code>NAN_SETTER</code></b></a>
  120. * <a href="#api_nan_property_getter"><b><code>NAN_PROPERTY_GETTER</code></b></a>
  121. * <a href="#api_nan_property_setter"><b><code>NAN_PROPERTY_SETTER</code></b></a>
  122. * <a href="#api_nan_property_enumerator"><b><code>NAN_PROPERTY_ENUMERATOR</code></b></a>
  123. * <a href="#api_nan_property_deleter"><b><code>NAN_PROPERTY_DELETER</code></b></a>
  124. * <a href="#api_nan_property_query"><b><code>NAN_PROPERTY_QUERY</code></b></a>
  125. * <a href="#api_nan_weak_callback"><b><code>NAN_WEAK_CALLBACK</code></b></a>
  126. * <a href="#api_nan_return_value"><b><code>NanReturnValue</code></b></a>
  127. * <a href="#api_nan_return_undefined"><b><code>NanReturnUndefined</code></b></a>
  128. * <a href="#api_nan_return_null"><b><code>NanReturnNull</code></b></a>
  129. * <a href="#api_nan_return_empty_string"><b><code>NanReturnEmptyString</code></b></a>
  130. * <a href="#api_nan_scope"><b><code>NanScope</code></b></a>
  131. * <a href="#api_nan_locker"><b><code>NanLocker</code></b></a>
  132. * <a href="#api_nan_unlocker"><b><code>NanUnlocker</code></b></a>
  133. * <a href="#api_nan_get_internal_field_pointer"><b><code>NanGetInternalFieldPointer</code></b></a>
  134. * <a href="#api_nan_set_internal_field_pointer"><b><code>NanSetInternalFieldPointer</code></b></a>
  135. * <a href="#api_nan_object_wrap_handle"><b><code>NanObjectWrapHandle</code></b></a>
  136. * <a href="#api_nan_make_weak"><b><code>NanMakeWeak</code></b></a>
  137. * <a href="#api_nan_symbol"><b><code>NanSymbol</code></b></a>
  138. * <a href="#api_nan_get_pointer_safe"><b><code>NanGetPointerSafe</code></b></a>
  139. * <a href="#api_nan_set_pointer_safe"><b><code>NanSetPointerSafe</code></b></a>
  140. * <a href="#api_nan_from_v8_string"><b><code>NanFromV8String</code></b></a>
  141. * <a href="#api_nan_boolean_option_value"><b><code>NanBooleanOptionValue</code></b></a>
  142. * <a href="#api_nan_uint32_option_value"><b><code>NanUInt32OptionValue</code></b></a>
  143. * <a href="#api_nan_throw_error"><b><code>NanThrowError</code></b>, <b><code>NanThrowTypeError</code></b>, <b><code>NanThrowRangeError</code></b>, <b><code>NanThrowError(Handle<Value>)</code></b>, <b><code>NanThrowError(Handle<Value>, int)</code></b></a>
  144. * <a href="#api_nan_new_buffer_handle"><b><code>NanNewBufferHandle(char *, size_t, FreeCallback, void *)</code></b>, <b><code>NanNewBufferHandle(char *, uint32_t)</code></b>, <b><code>NanNewBufferHandle(uint32_t)</code></b></a>
  145. * <a href="#api_nan_buffer_use"><b><code>NanBufferUse(char *, uint32_t)</code></b></a>
  146. * <a href="#api_nan_new_context_handle"><b><code>NanNewContextHandle</code></b></a>
  147. * <a href="#api_nan_has_instance"><b><code>NanHasInstance</code></b></a>
  148. * <a href="#api_nan_persistent_to_local"><b><code>NanPersistentToLocal</code></b></a>
  149. * <a href="#api_nan_dispose"><b><code>NanDispose</code></b></a>
  150. * <a href="#api_nan_assign_persistent"><b><code>NanAssignPersistent</code></b></a>
  151. * <a href="#api_nan_init_persistent"><b><code>NanInitPersistent</code></b></a>
  152. * <a href="#api_nan_callback"><b><code>NanCallback</code></b></a>
  153. * <a href="#api_nan_async_worker"><b><code>NanAsyncWorker</code></b></a>
  154. * <a href="#api_nan_async_queue_worker"><b><code>NanAsyncQueueWorker</code></b></a>
  155. <a name="api_nan_method"></a>
  156. ### NAN_METHOD(methodname)
  157. Use `NAN_METHOD` to define your V8 accessible methods:
  158. ```c++
  159. // .h:
  160. class Foo : public node::ObjectWrap {
  161. ...
  162. static NAN_METHOD(Bar);
  163. static NAN_METHOD(Baz);
  164. }
  165. // .cc:
  166. NAN_METHOD(Foo::Bar) {
  167. ...
  168. }
  169. NAN_METHOD(Foo::Baz) {
  170. ...
  171. }
  172. ```
  173. The reason for this macro is because of the method signature change in 0.11:
  174. ```c++
  175. // 0.10 and below:
  176. Handle<Value> name(const Arguments& args)
  177. // 0.11 and above
  178. void name(const FunctionCallbackInfo<Value>& args)
  179. ```
  180. The introduction of `FunctionCallbackInfo` brings additional complications:
  181. <a name="api_nan_getter"></a>
  182. ### NAN_GETTER(methodname)
  183. Use `NAN_GETTER` to declare your V8 accessible getters. You get a `Local<String>` `property` and an appropriately typed `args` object that can act like the `args` argument to a `NAN_METHOD` call.
  184. You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_GETTER`.
  185. <a name="api_nan_setter"></a>
  186. ### NAN_SETTER(methodname)
  187. Use `NAN_SETTER` to declare your V8 accessible setters. Same as `NAN_GETTER` but you also get a `Local<Value>` `value` object to work with.
  188. You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_SETTER`.
  189. <a name="api_nan_property_getter"></a>
  190. ### NAN_PROPERTY_GETTER(cbname)
  191. Use `NAN_PROPERTY_GETTER` to declare your V8 accessible property getters. You get a `Local<String>` `property` and an appropriately typed `args` object that can act similar to the `args` argument to a `NAN_METHOD` call.
  192. You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_PROPERTY_GETTER`.
  193. <a name="api_nan_property_setter"></a>
  194. ### NAN_PROPERTY_SETTER(cbname)
  195. Use `NAN_PROPERTY_SETTER` to declare your V8 accessible property setters. Same as `NAN_PROPERTY_GETTER` but you also get a `Local<Value>` `value` object to work with.
  196. You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_PROPERTY_SETTER`.
  197. <a name="api_nan_property_enumerator"></a>
  198. ### NAN_PROPERTY_ENUMERATOR(cbname)
  199. Use `NAN_PROPERTY_ENUMERATOR` to declare your V8 accessible property enumerators. You get an appropriately typed `args` object like the `args` argument to a `NAN_PROPERTY_GETTER` call.
  200. You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_PROPERTY_ENUMERATOR`.
  201. <a name="api_nan_property_deleter"></a>
  202. ### NAN_PROPERTY_DELETER(cbname)
  203. Use `NAN_PROPERTY_DELETER` to declare your V8 accessible property deleters. Same as `NAN_PROPERTY_GETTER`.
  204. You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_PROPERTY_DELETER`.
  205. <a name="api_nan_property_query"></a>
  206. ### NAN_PROPERTY_QUERY(cbname)
  207. Use `NAN_PROPERTY_QUERY` to declare your V8 accessible property queries. Same as `NAN_PROPERTY_GETTER`.
  208. You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_PROPERTY_QUERY`.
  209. <a name="api_nan_weak_callback"></a>
  210. ### NAN_WEAK_CALLBACK(type, cbname)
  211. Use `NAN_WEAK_CALLBACK` to declare your V8 WeakReference callbacks. There is an object argument accessible through `NAN_WEAK_CALLBACK_OBJECT`. The `type` argument gives the type of the `data` argument, accessible through `NAN_WEAK_CALLBACK_DATA(type)`.
  212. ```c++
  213. static NAN_WEAK_CALLBACK(BufferReference*, WeakCheck) {
  214. if (NAN_WEAK_CALLBACK_DATA(BufferReference*)->noLongerNeeded_) {
  215. delete NAN_WEAK_CALLBACK_DATA(BufferReference*);
  216. } else {
  217. // Still in use, revive, prevent GC
  218. NanMakeWeak(NAN_WEAK_CALLBACK_OBJECT, NAN_WEAK_CALLBACK_DATA(BufferReference*), &WeakCheck);
  219. }
  220. }
  221. ```
  222. <a name="api_nan_return_value"></a>
  223. ### NanReturnValue(Handle&lt;Value&gt;)
  224. Use `NanReturnValue` when you want to return a value from your V8 accessible method:
  225. ```c++
  226. NAN_METHOD(Foo::Bar) {
  227. ...
  228. NanReturnValue(String::New("FooBar!"));
  229. }
  230. ```
  231. No `return` statement required.
  232. <a name="api_nan_return_undefined"></a>
  233. ### NanReturnUndefined()
  234. Use `NanReturnUndefined` when you don't want to return anything from your V8 accessible method:
  235. ```c++
  236. NAN_METHOD(Foo::Baz) {
  237. ...
  238. NanReturnUndefined();
  239. }
  240. ```
  241. <a name="api_nan_return_null"></a>
  242. ### NanReturnNull()
  243. Use `NanReturnNull` when you want to return `Null` from your V8 accessible method:
  244. ```c++
  245. NAN_METHOD(Foo::Baz) {
  246. ...
  247. NanReturnNull();
  248. }
  249. ```
  250. <a name="api_nan_return_empty_string"></a>
  251. ### NanReturnEmptyString()
  252. Use `NanReturnEmptyString` when you want to return an empty `String` from your V8 accessible method:
  253. ```c++
  254. NAN_METHOD(Foo::Baz) {
  255. ...
  256. NanReturnEmptyString();
  257. }
  258. ```
  259. <a name="api_nan_scope"></a>
  260. ### NanScope()
  261. The introduction of `isolate` references for many V8 calls in Node 0.11 makes `NanScope()` necessary, use it in place of `HandleScope scope`:
  262. ```c++
  263. NAN_METHOD(Foo::Bar) {
  264. NanScope();
  265. NanReturnValue(String::New("FooBar!"));
  266. }
  267. ```
  268. <a name="api_nan_locker"></a>
  269. ### NanLocker()
  270. The introduction of `isolate` references for many V8 calls in Node 0.11 makes `NanLocker()` necessary, use it in place of `Locker locker`:
  271. ```c++
  272. NAN_METHOD(Foo::Bar) {
  273. NanLocker();
  274. ...
  275. NanUnlocker();
  276. }
  277. ```
  278. <a name="api_nan_unlocker"></a>
  279. ### NanUnlocker()
  280. The introduction of `isolate` references for many V8 calls in Node 0.11 makes `NanUnlocker()` necessary, use it in place of `Unlocker unlocker`:
  281. ```c++
  282. NAN_METHOD(Foo::Bar) {
  283. NanLocker();
  284. ...
  285. NanUnlocker();
  286. }
  287. ```
  288. <a name="api_nan_get_internal_field_pointer"></a>
  289. ### void * NanGetInternalFieldPointer(Handle&lt;Object&gt;, int)
  290. Gets a pointer to the internal field with at `index` from a V8 `Object` handle.
  291. ```c++
  292. Local<Object> obj;
  293. ...
  294. NanGetInternalFieldPointer(obj, 0);
  295. ```
  296. <a name="api_nan_set_internal_field_pointer"></a>
  297. ### void NanSetInternalFieldPointer(Handle&lt;Object&gt;, int, void *)
  298. Sets the value of the internal field at `index` on a V8 `Object` handle.
  299. ```c++
  300. static Persistent<Function> dataWrapperCtor;
  301. ...
  302. Local<Object> wrapper = NanPersistentToLocal(dataWrapperCtor)->NewInstance();
  303. NanSetInternalFieldPointer(wrapper, 0, this);
  304. ```
  305. <a name="api_nan_object_wrap_handle"></a>
  306. ### Local&lt;Object&gt; NanObjectWrapHandle(Object)
  307. When you want to fetch the V8 object handle from a native object you've wrapped with Node's `ObjectWrap`, you should use `NanObjectWrapHandle`:
  308. ```c++
  309. NanObjectWrapHandle(iterator)->Get(String::NewSymbol("end"))
  310. ```
  311. <a name="api_nan_make_weak"></a>
  312. ### NanMakeWeak(Persistent&lt;T&gt;, parameter, callback)
  313. Make a persistent reference weak.
  314. <a name="api_nan_symbol"></a>
  315. ### String NanSymbol(char *)
  316. This isn't strictly about compatibility, it's just an easier way to create string symbol objects (i.e. `String::NewSymbol(x)`), for getting and setting object properties, or names of objects.
  317. ```c++
  318. bool foo = false;
  319. if (obj->Has(NanSymbol("foo")))
  320. foo = optionsObj->Get(NanSymbol("foo"))->BooleanValue()
  321. ```
  322. <a name="api_nan_get_pointer_safe"></a>
  323. ### Type NanGetPointerSafe(Type *[, Type])
  324. A helper for getting values from optional pointers. If the pointer is `NULL`, the function returns the optional default value, which defaults to `0`. Otherwise, the function returns the value the pointer points to.
  325. ```c++
  326. char *plugh(uint32_t *optional) {
  327. char res[] = "xyzzy";
  328. uint32_t param = NanGetPointerSafe<uint32_t>(optional, 0x1337);
  329. switch (param) {
  330. ...
  331. }
  332. NanSetPointerSafe<uint32_t>(optional, 0xDEADBEEF);
  333. }
  334. ```
  335. <a name="api_nan_set_pointer_safe"></a>
  336. ### bool NanSetPointerSafe(Type *, Type)
  337. A helper for setting optional argument pointers. If the pointer is `NULL`, the function simply return `false`. Otherwise, the value is assigned to the variable the pointer points to.
  338. ```c++
  339. const char *plugh(size_t *outputsize) {
  340. char res[] = "xyzzy";
  341. if !(NanSetPointerSafe<size_t>(outputsize, strlen(res) + 1)) {
  342. ...
  343. }
  344. ...
  345. }
  346. ```
  347. <a name="api_nan_from_v8_string"></a>
  348. ### char* NanFromV8String(Handle&lt;Value&gt;[, enum Nan::Encoding, size_t *, char *, size_t, int])
  349. When you want to convert a V8 `String` to a `char*` use `NanFromV8String`. It is possible to define an encoding that defaults to `Nan::UTF8` as well as a pointer to a variable that will be assigned the number of bytes in the returned string. It is also possible to supply a buffer and its length to the function in order not to have a new buffer allocated. The final argument allows optionally setting `String::WriteOptions`, which default to `String::HINT_MANY_WRITES_EXPECTED | String::NO_NULL_TERMINATION`.
  350. Just remember that you'll end up with an object that you'll need to `delete[]` at some point unless you supply your own buffer:
  351. ```c++
  352. size_t count;
  353. char* name = NanFromV8String(args[0]);
  354. char* decoded = NanFromV8String(args[1], Nan::BASE64, &count, NULL, 0, String::HINT_MANY_WRITES_EXPECTED);
  355. char param_copy[count];
  356. memcpy(param_copy, decoded, count);
  357. delete[] decoded;
  358. ```
  359. <a name="api_nan_boolean_option_value"></a>
  360. ### bool NanBooleanOptionValue(Handle&lt;Value&gt;, Handle&lt;String&gt;[, bool])
  361. When you have an "options" object that you need to fetch properties from, boolean options can be fetched with this pair. They check first if the object exists (`IsEmpty`), then if the object has the given property (`Has`) then they get and convert/coerce the property to a `bool`.
  362. The optional last parameter is the *default* value, which is `false` if left off:
  363. ```c++
  364. // `foo` is false unless the user supplies a truthy value for it
  365. bool foo = NanBooleanOptionValue(optionsObj, NanSymbol("foo"));
  366. // `bar` is true unless the user supplies a falsy value for it
  367. bool bar = NanBooleanOptionValueDefTrue(optionsObj, NanSymbol("bar"), true);
  368. ```
  369. <a name="api_nan_uint32_option_value"></a>
  370. ### uint32_t NanUInt32OptionValue(Handle&lt;Value&gt;, Handle&lt;String&gt;, uint32_t)
  371. Similar to `NanBooleanOptionValue`, use `NanUInt32OptionValue` to fetch an integer option from your options object. Can be any kind of JavaScript `Number` and it will be coerced to an unsigned 32-bit integer.
  372. Requires all 3 arguments as a default is not optional:
  373. ```c++
  374. uint32_t count = NanUInt32OptionValue(optionsObj, NanSymbol("count"), 1024);
  375. ```
  376. <a name="api_nan_throw_error"></a>
  377. ### NanThrowError(message), NanThrowTypeError(message), NanThrowRangeError(message), NanThrowError(Local&lt;Value&gt;), NanThrowError(Local&lt;Value&gt;, int)
  378. For throwing `Error`, `TypeError` and `RangeError` objects. You should `return` this call:
  379. ```c++
  380. return NanThrowError("you must supply a callback argument");
  381. ```
  382. Can also handle any custom object you may want to throw. If used with the error code argument, it will add the supplied error code to the error object as a property called `code`.
  383. <a name="api_nan_new_buffer_handle"></a>
  384. ### Local&lt;Object&gt; NanNewBufferHandle(char *, uint32_t), Local&lt;Object&gt; NanNewBufferHandle(uint32_t)
  385. The `Buffer` API has changed a little in Node 0.11, this helper provides consistent access to `Buffer` creation:
  386. ```c++
  387. NanNewBufferHandle((char*)value.data(), value.size());
  388. ```
  389. Can also be used to initialize a `Buffer` with just a `size` argument.
  390. Can also be supplied with a `NAN_WEAK_CALLBACK` and a hint for the garbage collector, when dealing with weak references.
  391. <a name="api_nan_buffer_use"></a>
  392. ### Local&lt;Object&gt; NanBufferUse(char*, uint32_t)
  393. `Buffer::New(char*, uint32_t)` prior to 0.11 would make a copy of the data.
  394. While it was possible to get around this, it required a shim by passing a
  395. callback. So the new API `Buffer::Use(char*, uint32_t)` was introduced to remove
  396. needing to use this shim.
  397. `NanBufferUse` uses the `char*` passed as the backing data, and will free the
  398. memory automatically when the weak callback is called. Keep this in mind, as
  399. careless use can lead to "double free or corruption" and other cryptic failures.
  400. <a name="api_nan_has_instance"></a>
  401. ### bool NanHasInstance(Persistent&lt;FunctionTemplate&gt;&, Handle&lt;Value&gt;)
  402. Can be used to check the type of an object to determine it is of a particular class you have already defined and have a `Persistent<FunctionTemplate>` handle for.
  403. <a name="api_nan_persistent_to_local"></a>
  404. ### Local&lt;Type&gt; NanPersistentToLocal(Persistent&lt;Type&gt;&)
  405. Aside from `FunctionCallbackInfo`, the biggest and most painful change to V8 in Node 0.11 is the many restrictions now placed on `Persistent` handles. They are difficult to assign and difficult to fetch the original value out of.
  406. Use `NanPersistentToLocal` to convert a `Persistent` handle back to a `Local` handle.
  407. ```c++
  408. Local<Object> handle = NanPersistentToLocal(persistentHandle);
  409. ```
  410. <a href="#api_nan_new_context_handle">
  411. ### Local&lt;Context&gt; NanNewContextHandle([ExtensionConfiguration*, Handle&lt;ObjectTemplate&gt;, Handle&lt;Value&gt;])
  412. Creates a new `Local<Context>` handle.
  413. ```c++
  414. Local<FunctionTemplate> ftmpl = FunctionTemplate::New();
  415. Local<ObjectTemplate> otmpl = ftmpl->InstanceTemplate();
  416. Local<Context> ctx = NanNewContextHandle(NULL, otmpl);
  417. ```
  418. <a name="api_nan_dispose"></a>
  419. ### void NanDispose(Persistent&lt;T&gt; &)
  420. Use `NanDispose` to dispose a `Persistent` handle.
  421. ```c++
  422. NanDispose(persistentHandle);
  423. ```
  424. <a name="api_nan_assign_persistent"></a>
  425. ### NanAssignPersistent(type, handle, object)
  426. Use `NanAssignPersistent` to assign a non-`Persistent` handle to a `Persistent` one. You can no longer just declare a `Persistent` handle and assign directly to it later, you have to `Reset` it in Node 0.11, so this makes it easier.
  427. In general it is now better to place anything you want to protect from V8's garbage collector as properties of a generic `Object` and then assign that to a `Persistent`. This works in older versions of Node also if you use `NanAssignPersistent`:
  428. ```c++
  429. Persistent<Object> persistentHandle;
  430. ...
  431. Local<Object> obj = Object::New();
  432. obj->Set(NanSymbol("key"), keyHandle); // where keyHandle might be a Local<String>
  433. NanAssignPersistent(Object, persistentHandle, obj)
  434. ```
  435. <a name="api_nan_init_persistent"></a>
  436. ### NanInitPersistent(type, name, object)
  437. User `NanInitPersistent` to declare and initialize a new `Persistent` with the supplied object. The assignment operator for `Persistent` is no longer public in Node 0.11, so this macro makes it easier to declare and initializing a new `Persistent`. See <a href="#api_nan_assign_persistent"><b><code>NanAssignPersistent</code></b></a> for more information.
  438. ```c++
  439. Local<Object> obj = Object::New();
  440. obj->Set(NanSymbol("key"), keyHandle); // where keyHandle might be a Local<String>
  441. NanInitPersistent(Object, persistentHandle, obj);
  442. ```
  443. <a name="api_nan_callback"></a>
  444. ### NanCallback
  445. Because of the difficulties imposed by the changes to `Persistent` handles in V8 in Node 0.11, creating `Persistent` versions of your `Local<Function>` handles is annoyingly tricky. `NanCallback` makes it easier by taking your `Local` handle, making it persistent until the `NanCallback` is deleted and even providing a handy `Call()` method to fetch and execute the callback `Function`.
  446. ```c++
  447. Local<Function> callbackHandle = callback = args[0].As<Function>();
  448. NanCallback *callback = new NanCallback(callbackHandle);
  449. // pass `callback` around and it's safe from GC until you:
  450. delete callback;
  451. ```
  452. You can execute the callback like so:
  453. ```c++
  454. // no arguments:
  455. callback->Call(0, NULL);
  456. // an error argument:
  457. Local<Value> argv[] = {
  458. Exception::Error(String::New("fail!"))
  459. };
  460. callback->Call(1, argv);
  461. // a success argument:
  462. Local<Value> argv[] = {
  463. Local<Value>::New(Null()),
  464. String::New("w00t!")
  465. };
  466. callback->Call(2, argv);
  467. ```
  468. `NanCallback` also has a `Local<Function> GetCallback()` method that you can use to fetch a local handle to the underlying callback function if you need it.
  469. <a name="api_nan_async_worker"></a>
  470. ### NanAsyncWorker
  471. `NanAsyncWorker` is an abstract class that you can subclass to have much of the annoying async queuing and handling taken care of for you. It can even store arbitrary V8 objects for you and have them persist while the async work is in progress.
  472. See a rough outline of the implementation:
  473. ```c++
  474. class NanAsyncWorker {
  475. public:
  476. NanAsyncWorker (NanCallback *callback);
  477. // Clean up persistent handles and delete the *callback
  478. virtual ~NanAsyncWorker ();
  479. // Check the `char *errmsg` property and call HandleOKCallback()
  480. // or HandleErrorCallback depending on whether it has been set or not
  481. virtual void WorkComplete ();
  482. // You must implement this to do some async work. If there is an
  483. // error then allocate `errmsg` to to a message and the callback will
  484. // be passed that string in an Error object
  485. virtual void Execute ();
  486. protected:
  487. // Set this if there is an error, otherwise it's NULL
  488. const char *errmsg;
  489. // Save a V8 object in a Persistent handle to protect it from GC
  490. void SavePersistent(const char *key, Local<Object> &obj);
  491. // Fetch a stored V8 object (don't call from within `Execute()`)
  492. Local<Object> GetFromPersistent(const char *key);
  493. // Default implementation calls the callback function with no arguments.
  494. // Override this to return meaningful data
  495. virtual void HandleOKCallback ();
  496. // Default implementation calls the callback function with an Error object
  497. // wrapping the `errmsg` string
  498. virtual void HandleErrorCallback ();
  499. };
  500. ```
  501. <a name="api_nan_async_queue_worker"></a>
  502. ### NanAsyncQueueWorker(NanAsyncWorker *)
  503. `NanAsyncQueueWorker` will run a `NanAsyncWorker` asynchronously via libuv. Both the *execute* and *after_work* steps are taken care of for you&mdash;most of the logic for this is embedded in `NanAsyncWorker`.
  504. ### Contributors
  505. NAN is only possible due to the excellent work of the following contributors:
  506. <table><tbody>
  507. <tr><th align="left">Rod Vagg</th><td><a href="https://github.com/rvagg">GitHub/rvagg</a></td><td><a href="http://twitter.com/rvagg">Twitter/@rvagg</a></td></tr>
  508. <tr><th align="left">Benjamin Byholm</th><td><a href="https://github.com/kkoopa/">GitHub/kkoopa</a></td></tr>
  509. <tr><th align="left">Trevor Norris</th><td><a href="https://github.com/trevnorris">GitHub/trevnorris</a></td><td><a href="http://twitter.com/trevnorris">Twitter/@trevnorris</a></td></tr>
  510. </tbody></table>
  511. Licence &amp; copyright
  512. -----------------------
  513. Copyright (c) 2013 Rod Vagg & NAN contributors (listed above).
  514. Native Abstractions for Node.js is licensed under an MIT +no-false-attribs license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE file for more details.