raspberryGPIOhtmlserver/node_modules/nan/README.md
node_modules/nan/README.mdRaw
1Native Abstractions for Node.js
2===============================
3
4**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.**
5
6***Current version: 0.3.2*** *(See [nan.h](https://github.com/rvagg/nan/blob/master/nan.h) for changelog)*
7
8[](https://nodei.co/npm/nan/) [](https://nodei.co/npm/nan/)
9
10Thanks 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.
11
12This project also contains some helper utilities that make addon development a bit more pleasant.
13
14 * **[Usage](#usage)**
15 * **[Example](#example)**
16 * **[API](#api)**
17
18<a name="usage"></a>
19## Usage
20
21Simply add **NAN** as a dependency in the *package.json* of your Node addon:
22
23```js
24"dependencies": {
25 ...
26 "nan" : "~0.3.1"
27 ...
28}
29```
30
31Pull in the path to **NAN** in your *binding.gyp* so that you can use `#include "nan.h"` in your *.cpp*:
32
33```js
34"include_dirs" : [
35 ...
36 "<!(node -p -e \"require('path').dirname(require.resolve('nan'))\")"
37 ...
38]
39```
40
41This works like a `-I<path-to-NAN>` when compiling your addon.
42
43<a name="example"></a>
44## Example
45
46See **[LevelDOWN](https://github.com/rvagg/node-leveldown/pull/48)** for a full example of **NAN** in use.
47
48For 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**.
49
50Compare 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).
51
52Note 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.
53
54```c++
55// addon.cc
56#include <node.h>
57#include "nan.h"
58// ...
59
60using namespace v8;
61
62void InitAll(Handle<Object> exports) {
63 exports->Set(NanSymbol("calculateSync"),
64 FunctionTemplate::New(CalculateSync)->GetFunction());
65
66 exports->Set(NanSymbol("calculateAsync"),
67 FunctionTemplate::New(CalculateAsync)->GetFunction());
68}
69
70NODE_MODULE(addon, InitAll)
71```
72
73```c++
74// sync.h
75#include <node.h>
76#include "nan.h"
77
78NAN_METHOD(CalculateSync);
79```
80
81```c++
82// sync.cc
83#include <node.h>
84#include "nan.h"
85#include "sync.h"
86// ...
87
88using namespace v8;
89
90// Simple synchronous access to the `Estimate()` function
91NAN_METHOD(CalculateSync) {
92 NanScope();
93
94 // expect a number as the first argument
95 int points = args[0]->Uint32Value();
96 double est = Estimate(points);
97
98 NanReturnValue(Number::New(est));
99}
100```
101
102```c++
103// async.cc
104#include <node.h>
105#include "nan.h"
106#include "async.h"
107
108// ...
109
110using namespace v8;
111
112class PiWorker : public NanAsyncWorker {
113 public:
114 PiWorker(NanCallback *callback, int points)
115 : NanAsyncWorker(callback), points(points) {}
116 ~PiWorker() {}
117
118 // Executed inside the worker-thread.
119 // It is not safe to access V8, or V8 data structures
120 // here, so everything we need for input and output
121 // should go on `this`.
122 void Execute () {
123 estimate = Estimate(points);
124 }
125
126 // Executed when the async work is complete
127 // this function will be run inside the main event loop
128 // so it is safe to use V8 again
129 void HandleOKCallback () {
130 NanScope();
131
132 Local<Value> argv[] = {
133 Local<Value>::New(Null())
134 , Number::New(estimate)
135 };
136
137 callback->Call(2, argv);
138 };
139
140 private:
141 int points;
142 double estimate;
143};
144
145// Asynchronous access to the `Estimate()` function
146NAN_METHOD(CalculateAsync) {
147 NanScope();
148
149 int points = args[0]->Uint32Value();
150 NanCallback *callback = new NanCallback(args[1].As<Function>());
151
152 NanAsyncQueueWorker(new PiWorker(callback, points));
153 NanReturnUndefined();
154}
155```
156
157<a name="api"></a>
158## API
159
160 * <a href="#api_nan_method"><b><code>NAN_METHOD</code></b></a>
161 * <a href="#api_nan_getter"><b><code>NAN_GETTER</code></b></a>
162 * <a href="#api_nan_setter"><b><code>NAN_SETTER</code></b></a>
163 * <a href="#api_nan_property_getter"><b><code>NAN_PROPERTY_GETTER</code></b></a>
164 * <a href="#api_nan_property_setter"><b><code>NAN_PROPERTY_SETTER</code></b></a>
165 * <a href="#api_nan_property_enumerator"><b><code>NAN_PROPERTY_ENUMERATOR</code></b></a>
166 * <a href="#api_nan_property_deleter"><b><code>NAN_PROPERTY_DELETER</code></b></a>
167 * <a href="#api_nan_property_query"><b><code>NAN_PROPERTY_QUERY</code></b></a>
168 * <a href="#api_nan_weak_callback"><b><code>NAN_WEAK_CALLBACK</code></b></a>
169 * <a href="#api_nan_return_value"><b><code>NanReturnValue</code></b></a>
170 * <a href="#api_nan_return_undefined"><b><code>NanReturnUndefined</code></b></a>
171 * <a href="#api_nan_return_null"><b><code>NanReturnNull</code></b></a>
172 * <a href="#api_nan_return_empty_string"><b><code>NanReturnEmptyString</code></b></a>
173 * <a href="#api_nan_scope"><b><code>NanScope</code></b></a>
174 * <a href="#api_nan_locker"><b><code>NanLocker</code></b></a>
175 * <a href="#api_nan_unlocker"><b><code>NanUnlocker</code></b></a>
176 * <a href="#api_nan_get_internal_field_pointer"><b><code>NanGetInternalFieldPointer</code></b></a>
177 * <a href="#api_nan_set_internal_field_pointer"><b><code>NanSetInternalFieldPointer</code></b></a>
178 * <a href="#api_nan_object_wrap_handle"><b><code>NanObjectWrapHandle</code></b></a>
179 * <a href="#api_nan_make_weak"><b><code>NanMakeWeak</code></b></a>
180 * <a href="#api_nan_symbol"><b><code>NanSymbol</code></b></a>
181 * <a href="#api_nan_get_pointer_safe"><b><code>NanGetPointerSafe</code></b></a>
182 * <a href="#api_nan_set_pointer_safe"><b><code>NanSetPointerSafe</code></b></a>
183 * <a href="#api_nan_from_v8_string"><b><code>NanFromV8String</code></b></a>
184 * <a href="#api_nan_boolean_option_value"><b><code>NanBooleanOptionValue</code></b></a>
185 * <a href="#api_nan_uint32_option_value"><b><code>NanUInt32OptionValue</code></b></a>
186 * <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>
187 * <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>
188 * <a href="#api_nan_buffer_use"><b><code>NanBufferUse(char *, uint32_t)</code></b></a>
189 * <a href="#api_nan_new_context_handle"><b><code>NanNewContextHandle</code></b></a>
190 * <a href="#api_nan_has_instance"><b><code>NanHasInstance</code></b></a>
191 * <a href="#api_nan_persistent_to_local"><b><code>NanPersistentToLocal</code></b></a>
192 * <a href="#api_nan_dispose"><b><code>NanDispose</code></b></a>
193 * <a href="#api_nan_assign_persistent"><b><code>NanAssignPersistent</code></b></a>
194 * <a href="#api_nan_init_persistent"><b><code>NanInitPersistent</code></b></a>
195 * <a href="#api_nan_callback"><b><code>NanCallback</code></b></a>
196 * <a href="#api_nan_async_worker"><b><code>NanAsyncWorker</code></b></a>
197 * <a href="#api_nan_async_queue_worker"><b><code>NanAsyncQueueWorker</code></b></a>
198
199<a name="api_nan_method"></a>
200### NAN_METHOD(methodname)
201
202Use `NAN_METHOD` to define your V8 accessible methods:
203
204```c++
205// .h:
206class Foo : public node::ObjectWrap {
207 ...
208
209 static NAN_METHOD(Bar);
210 static NAN_METHOD(Baz);
211}
212
213
214// .cc:
215NAN_METHOD(Foo::Bar) {
216 ...
217}
218
219NAN_METHOD(Foo::Baz) {
220 ...
221}
222```
223
224The reason for this macro is because of the method signature change in 0.11:
225
226```c++
227// 0.10 and below:
228Handle<Value> name(const Arguments& args)
229
230// 0.11 and above
231void name(const FunctionCallbackInfo<Value>& args)
232```
233
234The introduction of `FunctionCallbackInfo` brings additional complications:
235
236<a name="api_nan_getter"></a>
237### NAN_GETTER(methodname)
238
239Use `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.
240
241You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_GETTER`.
242
243<a name="api_nan_setter"></a>
244### NAN_SETTER(methodname)
245
246Use `NAN_SETTER` to declare your V8 accessible setters. Same as `NAN_GETTER` but you also get a `Local<Value>` `value` object to work with.
247
248You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_SETTER`.
249
250<a name="api_nan_property_getter"></a>
251### NAN_PROPERTY_GETTER(cbname)
252Use `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.
253
254You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_PROPERTY_GETTER`.
255
256<a name="api_nan_property_setter"></a>
257### NAN_PROPERTY_SETTER(cbname)
258Use `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.
259
260You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_PROPERTY_SETTER`.
261
262<a name="api_nan_property_enumerator"></a>
263### NAN_PROPERTY_ENUMERATOR(cbname)
264Use `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.
265
266You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_PROPERTY_ENUMERATOR`.
267
268<a name="api_nan_property_deleter"></a>
269### NAN_PROPERTY_DELETER(cbname)
270Use `NAN_PROPERTY_DELETER` to declare your V8 accessible property deleters. Same as `NAN_PROPERTY_GETTER`.
271
272You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_PROPERTY_DELETER`.
273
274<a name="api_nan_property_query"></a>
275### NAN_PROPERTY_QUERY(cbname)
276Use `NAN_PROPERTY_QUERY` to declare your V8 accessible property queries. Same as `NAN_PROPERTY_GETTER`.
277
278You can use `NanReturnNull()`, `NanReturnEmptyString()`, `NanReturnUndefined()` and `NanReturnValue()` in a `NAN_PROPERTY_QUERY`.
279
280<a name="api_nan_weak_callback"></a>
281### NAN_WEAK_CALLBACK(type, cbname)
282
283Use `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)`.
284
285```c++
286static NAN_WEAK_CALLBACK(BufferReference*, WeakCheck) {
287 if (NAN_WEAK_CALLBACK_DATA(BufferReference*)->noLongerNeeded_) {
288 delete NAN_WEAK_CALLBACK_DATA(BufferReference*);
289 } else {
290 // Still in use, revive, prevent GC
291 NanMakeWeak(NAN_WEAK_CALLBACK_OBJECT, NAN_WEAK_CALLBACK_DATA(BufferReference*), &WeakCheck);
292 }
293}
294
295```
296<a name="api_nan_return_value"></a>
297### NanReturnValue(Handle<Value>)
298
299Use `NanReturnValue` when you want to return a value from your V8 accessible method:
300
301```c++
302NAN_METHOD(Foo::Bar) {
303 ...
304
305 NanReturnValue(String::New("FooBar!"));
306}
307```
308
309No `return` statement required.
310
311<a name="api_nan_return_undefined"></a>
312### NanReturnUndefined()
313
314Use `NanReturnUndefined` when you don't want to return anything from your V8 accessible method:
315
316```c++
317NAN_METHOD(Foo::Baz) {
318 ...
319
320 NanReturnUndefined();
321}
322```
323
324<a name="api_nan_return_null"></a>
325### NanReturnNull()
326
327Use `NanReturnNull` when you want to return `Null` from your V8 accessible method:
328
329```c++
330NAN_METHOD(Foo::Baz) {
331 ...
332
333 NanReturnNull();
334}
335```
336
337<a name="api_nan_return_empty_string"></a>
338### NanReturnEmptyString()
339
340Use `NanReturnEmptyString` when you want to return an empty `String` from your V8 accessible method:
341
342```c++
343NAN_METHOD(Foo::Baz) {
344 ...
345
346 NanReturnEmptyString();
347}
348```
349
350<a name="api_nan_scope"></a>
351### NanScope()
352
353The introduction of `isolate` references for many V8 calls in Node 0.11 makes `NanScope()` necessary, use it in place of `HandleScope scope`:
354
355```c++
356NAN_METHOD(Foo::Bar) {
357 NanScope();
358
359 NanReturnValue(String::New("FooBar!"));
360}
361```
362
363<a name="api_nan_locker"></a>
364### NanLocker()
365
366The introduction of `isolate` references for many V8 calls in Node 0.11 makes `NanLocker()` necessary, use it in place of `Locker locker`:
367
368```c++
369NAN_METHOD(Foo::Bar) {
370 NanLocker();
371 ...
372 NanUnlocker();
373}
374```
375
376<a name="api_nan_unlocker"></a>
377### NanUnlocker()
378
379The introduction of `isolate` references for many V8 calls in Node 0.11 makes `NanUnlocker()` necessary, use it in place of `Unlocker unlocker`:
380
381```c++
382NAN_METHOD(Foo::Bar) {
383 NanLocker();
384 ...
385 NanUnlocker();
386}
387```
388
389<a name="api_nan_get_internal_field_pointer"></a>
390### void * NanGetInternalFieldPointer(Handle<Object>, int)
391
392Gets a pointer to the internal field with at `index` from a V8 `Object` handle.
393
394```c++
395Local<Object> obj;
396...
397NanGetInternalFieldPointer(obj, 0);
398```
399<a name="api_nan_set_internal_field_pointer"></a>
400### void NanSetInternalFieldPointer(Handle<Object>, int, void *)
401
402Sets the value of the internal field at `index` on a V8 `Object` handle.
403
404```c++
405static Persistent<Function> dataWrapperCtor;
406...
407Local<Object> wrapper = NanPersistentToLocal(dataWrapperCtor)->NewInstance();
408NanSetInternalFieldPointer(wrapper, 0, this);
409```
410
411<a name="api_nan_object_wrap_handle"></a>
412### Local<Object> NanObjectWrapHandle(Object)
413
414When you want to fetch the V8 object handle from a native object you've wrapped with Node's `ObjectWrap`, you should use `NanObjectWrapHandle`:
415
416```c++
417NanObjectWrapHandle(iterator)->Get(String::NewSymbol("end"))
418```
419
420<a name="api_nan_make_weak"></a>
421### NanMakeWeak(Persistent<T>, parameter, callback)
422
423Make a persistent reference weak.
424
425<a name="api_nan_symbol"></a>
426### String NanSymbol(char *)
427
428This 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.
429
430```c++
431bool foo = false;
432if (obj->Has(NanSymbol("foo")))
433 foo = optionsObj->Get(NanSymbol("foo"))->BooleanValue()
434```
435
436<a name="api_nan_get_pointer_safe"></a>
437### Type NanGetPointerSafe(Type *[, Type])
438
439A 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.
440
441```c++
442char *plugh(uint32_t *optional) {
443 char res[] = "xyzzy";
444 uint32_t param = NanGetPointerSafe<uint32_t>(optional, 0x1337);
445 switch (param) {
446 ...
447 }
448 NanSetPointerSafe<uint32_t>(optional, 0xDEADBEEF);
449}
450```
451
452<a name="api_nan_set_pointer_safe"></a>
453### bool NanSetPointerSafe(Type *, Type)
454
455A 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.
456
457```c++
458const char *plugh(size_t *outputsize) {
459 char res[] = "xyzzy";
460 if !(NanSetPointerSafe<size_t>(outputsize, strlen(res) + 1)) {
461 ...
462 }
463
464 ...
465}
466```
467
468<a name="api_nan_from_v8_string"></a>
469### char* NanFromV8String(Handle<Value>[, enum Nan::Encoding, size_t *, char *, size_t, int])
470
471When 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`.
472Just remember that you'll end up with an object that you'll need to `delete[]` at some point unless you supply your own buffer:
473
474```c++
475size_t count;
476char* name = NanFromV8String(args[0]);
477char* decoded = NanFromV8String(args[1], Nan::BASE64, &count, NULL, 0, String::HINT_MANY_WRITES_EXPECTED);
478char param_copy[count];
479memcpy(param_copy, decoded, count);
480delete[] decoded;
481```
482
483<a name="api_nan_boolean_option_value"></a>
484### bool NanBooleanOptionValue(Handle<Value>, Handle<String>[, bool])
485
486When 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`.
487
488The optional last parameter is the *default* value, which is `false` if left off:
489
490```c++
491// `foo` is false unless the user supplies a truthy value for it
492bool foo = NanBooleanOptionValue(optionsObj, NanSymbol("foo"));
493// `bar` is true unless the user supplies a falsy value for it
494bool bar = NanBooleanOptionValueDefTrue(optionsObj, NanSymbol("bar"), true);
495```
496
497<a name="api_nan_uint32_option_value"></a>
498### uint32_t NanUInt32OptionValue(Handle<Value>, Handle<String>, uint32_t)
499
500Similar 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.
501
502Requires all 3 arguments as a default is not optional:
503
504```c++
505uint32_t count = NanUInt32OptionValue(optionsObj, NanSymbol("count"), 1024);
506```
507
508<a name="api_nan_throw_error"></a>
509### NanThrowError(message), NanThrowTypeError(message), NanThrowRangeError(message), NanThrowError(Local<Value>), NanThrowError(Local<Value>, int)
510
511For throwing `Error`, `TypeError` and `RangeError` objects. You should `return` this call:
512
513```c++
514return NanThrowError("you must supply a callback argument");
515```
516
517Can 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`.
518
519<a name="api_nan_new_buffer_handle"></a>
520### Local<Object> NanNewBufferHandle(char *, uint32_t), Local<Object> NanNewBufferHandle(uint32_t)
521
522The `Buffer` API has changed a little in Node 0.11, this helper provides consistent access to `Buffer` creation:
523
524```c++
525NanNewBufferHandle((char*)value.data(), value.size());
526```
527
528Can also be used to initialize a `Buffer` with just a `size` argument.
529
530Can also be supplied with a `NAN_WEAK_CALLBACK` and a hint for the garbage collector, when dealing with weak references.
531
532<a name="api_nan_buffer_use"></a>
533### Local<Object> NanBufferUse(char*, uint32_t)
534
535`Buffer::New(char*, uint32_t)` prior to 0.11 would make a copy of the data.
536While it was possible to get around this, it required a shim by passing a
537callback. So the new API `Buffer::Use(char*, uint32_t)` was introduced to remove
538needing to use this shim.
539
540`NanBufferUse` uses the `char*` passed as the backing data, and will free the
541memory automatically when the weak callback is called. Keep this in mind, as
542careless use can lead to "double free or corruption" and other cryptic failures.
543
544<a name="api_nan_has_instance"></a>
545### bool NanHasInstance(Persistent<FunctionTemplate>&, Handle<Value>)
546
547Can 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.
548
549<a name="api_nan_persistent_to_local"></a>
550### Local<Type> NanPersistentToLocal(Persistent<Type>&)
551
552Aside 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.
553
554Use `NanPersistentToLocal` to convert a `Persistent` handle back to a `Local` handle.
555
556```c++
557Local<Object> handle = NanPersistentToLocal(persistentHandle);
558```
559
560<a href="#api_nan_new_context_handle">
561### Local<Context> NanNewContextHandle([ExtensionConfiguration*, Handle<ObjectTemplate>, Handle<Value>])
562Creates a new `Local<Context>` handle.
563
564```c++
565Local<FunctionTemplate> ftmpl = FunctionTemplate::New();
566Local<ObjectTemplate> otmpl = ftmpl->InstanceTemplate();
567Local<Context> ctx = NanNewContextHandle(NULL, otmpl);
568```
569
570<a name="api_nan_dispose"></a>
571### void NanDispose(Persistent<T> &)
572
573Use `NanDispose` to dispose a `Persistent` handle.
574
575```c++
576NanDispose(persistentHandle);
577```
578
579<a name="api_nan_assign_persistent"></a>
580### NanAssignPersistent(type, handle, object)
581
582Use `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.
583
584In 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`:
585
586```c++
587Persistent<Object> persistentHandle;
588
589...
590
591Local<Object> obj = Object::New();
592obj->Set(NanSymbol("key"), keyHandle); // where keyHandle might be a Local<String>
593NanAssignPersistent(Object, persistentHandle, obj)
594```
595
596<a name="api_nan_init_persistent"></a>
597### NanInitPersistent(type, name, object)
598
599User `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.
600
601```c++
602Local<Object> obj = Object::New();
603obj->Set(NanSymbol("key"), keyHandle); // where keyHandle might be a Local<String>
604NanInitPersistent(Object, persistentHandle, obj);
605```
606
607<a name="api_nan_callback"></a>
608### NanCallback
609
610Because 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`.
611
612```c++
613Local<Function> callbackHandle = callback = args[0].As<Function>();
614NanCallback *callback = new NanCallback(callbackHandle);
615// pass `callback` around and it's safe from GC until you:
616delete callback;
617```
618
619You can execute the callback like so:
620
621```c++
622// no arguments:
623callback->Call(0, NULL);
624
625// an error argument:
626Local<Value> argv[] = {
627 Exception::Error(String::New("fail!"))
628};
629callback->Call(1, argv);
630
631// a success argument:
632Local<Value> argv[] = {
633 Local<Value>::New(Null()),
634 String::New("w00t!")
635};
636callback->Call(2, argv);
637```
638
639`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.
640
641<a name="api_nan_async_worker"></a>
642### NanAsyncWorker
643
644`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.
645
646See a rough outline of the implementation:
647
648```c++
649class NanAsyncWorker {
650public:
651 NanAsyncWorker (NanCallback *callback);
652
653 // Clean up persistent handles and delete the *callback
654 virtual ~NanAsyncWorker ();
655
656 // Check the `char *errmsg` property and call HandleOKCallback()
657 // or HandleErrorCallback depending on whether it has been set or not
658 virtual void WorkComplete ();
659
660 // You must implement this to do some async work. If there is an
661 // error then allocate `errmsg` to to a message and the callback will
662 // be passed that string in an Error object
663 virtual void Execute ();
664
665protected:
666 // Set this if there is an error, otherwise it's NULL
667 const char *errmsg;
668
669 // Save a V8 object in a Persistent handle to protect it from GC
670 void SavePersistent(const char *key, Local<Object> &obj);
671
672 // Fetch a stored V8 object (don't call from within `Execute()`)
673 Local<Object> GetFromPersistent(const char *key);
674
675 // Default implementation calls the callback function with no arguments.
676 // Override this to return meaningful data
677 virtual void HandleOKCallback ();
678
679 // Default implementation calls the callback function with an Error object
680 // wrapping the `errmsg` string
681 virtual void HandleErrorCallback ();
682};
683```
684
685<a name="api_nan_async_queue_worker"></a>
686### NanAsyncQueueWorker(NanAsyncWorker *)
687
688`NanAsyncQueueWorker` will run a `NanAsyncWorker` asynchronously via libuv. Both the *execute* and *after_work* steps are taken care of for you—most of the logic for this is embedded in `NanAsyncWorker`.
689
690### Contributors
691
692NAN is only possible due to the excellent work of the following contributors:
693
694<table><tbody>
695<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>
696<tr><th align="left">Benjamin Byholm</th><td><a href="https://github.com/kkoopa/">GitHub/kkoopa</a></td></tr>
697<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>
698</tbody></table>
699
700Licence & copyright
701-----------------------
702
703Copyright (c) 2013 Rod Vagg & NAN contributors (listed above).
704
705Native 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.