Native Abstractions for Node.js =============================== **A header file filled with macro and utility goodness for making add-on development for Node.js easier across versions 0.8, 0.10, 0.12, 1, 4, 5, 6 and 7.** ***Current version: 2.5.0*** *(See [CHANGELOG.md](https://github.com/nodejs/nan/blob/master/CHANGELOG.md) for complete ChangeLog)* [![NPM](https://nodei.co/npm/nan.png?downloads=true&downloadRank=true)](https://nodei.co/npm/nan/) [![NPM](https://nodei.co/npm-dl/nan.png?months=6&height=3)](https://nodei.co/npm/nan/) [![Build Status](https://api.travis-ci.org/nodejs/nan.svg?branch=master)](http://travis-ci.org/nodejs/nan) [![Build status](https://ci.appveyor.com/api/projects/status/kh73pbm9dsju7fgh)](https://ci.appveyor.com/project/RodVagg/nan) Thanks to the crazy changes in V8 (and some in Node core), keeping native addons compiling happily across versions, particularly 0.10 to 0.12 to 4.0, 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. This project also contains some helper utilities that make addon development a bit more pleasant. * **[News & Updates](#news)** * **[Usage](#usage)** * **[Example](#example)** * **[API](#api)** * **[Tests](#tests)** * **[Governance & Contributing](#governance)** ## News & Updates ## Usage Simply add **NAN** as a dependency in the *package.json* of your Node addon: ``` bash $ npm install --save nan ``` Pull in the path to **NAN** in your *binding.gyp* so that you can use `#include ` in your *.cpp* files: ``` python "include_dirs" : [ "` when compiling your addon. ## Example Just getting started with Nan? Take a look at the **[Node Add-on Examples](https://github.com/nodejs/node-addon-examples)**. Refer to a [quick-start **Nan** Boilerplate](https://github.com/fcanas/node-native-boilerplate) for a ready-to-go project that utilizes basic Nan functionality. For a simpler example, see the **[async pi estimation example](https://github.com/nodejs/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**. Yet another example is **[nan-example-eol](https://github.com/CodeCharmLtd/nan-example-eol)**. It shows newline detection implemented as a native addon. Also take a look at our comprehensive **[C++ test suite](https://github.com/nodejs/nan/tree/master/test/cpp)** which has a plethora of code snippets for your pasting pleasure. ## API Additional to the NAN documentation below, please consult: * [The V8 Getting Started * Guide](https://github.com/v8/v8/wiki/Getting%20Started%20with%20Embedding) * [The V8 Embedders * Guide](https://github.com/v8/v8/wiki/Embedder%27s%20Guide) * [V8 API Documentation](http://v8docs.nodesource.com/) * [Node Add-on Documentation](https://nodejs.org/api/addons.html) ### JavaScript-accessible methods A _template_ is a blueprint for JavaScript functions and objects in a context. You can use a template to wrap C++ functions and data structures within JavaScript objects so that they can be manipulated from JavaScript. See the V8 Embedders Guide section on [Templates](https://developers.google.com/v8/embed#templates) for further information. In order to expose functionality to JavaScript via a template, you must provide it to V8 in a form that it understands. Across the versions of V8 supported by NAN, JavaScript-accessible method signatures vary widely, NAN fully abstracts method declaration and provides you with an interface that is similar to the most recent V8 API but is backward-compatible with older versions that still use the now-deceased `v8::Argument` type. * **Method argument types** - Nan::FunctionCallbackInfo - Nan::PropertyCallbackInfo - Nan::ReturnValue * **Method declarations** - Method declaration - Getter declaration - Setter declaration - Property getter declaration - Property setter declaration - Property enumerator declaration - Property deleter declaration - Property query declaration - Index getter declaration - Index setter declaration - Index enumerator declaration - Index deleter declaration - Index query declaration * Method and template helpers - Nan::SetMethod() - Nan::SetPrototypeMethod() - Nan::SetAccessor() - Nan::SetNamedPropertyHandler() - Nan::SetIndexedPropertyHandler() - Nan::SetTemplate() - Nan::SetPrototypeTemplate() - Nan::SetInstanceTemplate() - Nan::SetCallHandler() - Nan::SetCallAsFunctionHandler() ### Scopes A _local handle_ is a pointer to an object. All V8 objects are accessed using handles, they are necessary because of the way the V8 garbage collector works. A handle scope can be thought of as a container for any number of handles. When you've finished with your handles, instead of deleting each one individually you can simply delete their scope. The creation of `HandleScope` objects is different across the supported versions of V8. Therefore, NAN provides its own implementations that can be used safely across these. - Nan::HandleScope - Nan::EscapableHandleScope Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://github.com/v8/v8/wiki/Embedder%27s%20Guide#handles-and-garbage-collection). ### Persistent references An object reference that is independent of any `HandleScope` is a _persistent_ reference. Where a `Local` handle only lives as long as the `HandleScope` in which it was allocated, a `Persistent` handle remains valid until it is explicitly disposed. Due to the evolution of the V8 API, it is necessary for NAN to provide a wrapper implementation of the `Persistent` classes to supply compatibility across the V8 versions supported. - Nan::PersistentBase & v8::PersistentBase - Nan::NonCopyablePersistentTraits & v8::NonCopyablePersistentTraits - Nan::CopyablePersistentTraits & v8::CopyablePersistentTraits - Nan::Persistent - Nan::Global - Nan::WeakCallbackInfo - Nan::WeakCallbackType Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://developers.google.com/v8/embed#handles). ### New NAN provides a `Nan::New()` helper for the creation of new JavaScript objects in a way that's compatible across the supported versions of V8. - Nan::New() - Nan::Undefined() - Nan::Null() - Nan::True() - Nan::False() - Nan::EmptyString() ### Converters NAN contains functions that convert `v8::Value`s to other `v8::Value` types and native types. Since type conversion is not guaranteed to succeed, they return `Nan::Maybe` types. These converters can be used in place of `value->ToX()` and `value->XValue()` (where `X` is one of the types, e.g. `Boolean`) in a way that provides a consistent interface across V8 versions. Newer versions of V8 use the new `v8::Maybe` and `v8::MaybeLocal` types for these conversions, older versions don't have this functionality so it is provided by NAN. - Nan::To() ### Maybe Types The `Nan::MaybeLocal` and `Nan::Maybe` types are monads that encapsulate `v8::Local` handles that _may be empty_. * **Maybe Types** - Nan::MaybeLocal - Nan::Maybe - Nan::Nothing - Nan::Just * **Maybe Helpers** - Nan::Call() - Nan::ToDetailString() - Nan::ToArrayIndex() - Nan::Equals() - Nan::NewInstance() - Nan::GetFunction() - Nan::Set() - Nan::ForceSet() - Nan::Get() - Nan::GetPropertyAttributes() - Nan::Has() - Nan::Delete() - Nan::GetPropertyNames() - Nan::GetOwnPropertyNames() - Nan::SetPrototype() - Nan::ObjectProtoToString() - Nan::HasOwnProperty() - Nan::HasRealNamedProperty() - Nan::HasRealIndexedProperty() - Nan::HasRealNamedCallbackProperty() - Nan::GetRealNamedPropertyInPrototypeChain() - Nan::GetRealNamedProperty() - Nan::CallAsFunction() - Nan::CallAsConstructor() - Nan::GetSourceLine() - Nan::GetLineNumber() - Nan::GetStartColumn() - Nan::GetEndColumn() - Nan::CloneElementAt() - Nan::HasPrivate() - Nan::GetPrivate() - Nan::SetPrivate() - Nan::DeletePrivate() - Nan::MakeMaybe() ### Script NAN provides a `v8::Script` helpers as the API has changed over the supported versions of V8. - Nan::CompileScript() - Nan::RunScript() ### Errors NAN includes helpers for creating, throwing and catching Errors as much of this functionality varies across the supported versions of V8 and must be abstracted. Note that an Error object is simply a specialized form of `v8::Value`. Also consult the V8 Embedders Guide section on [Exceptions](https://developers.google.com/v8/embed#exceptions) for more information. - Nan::Error() - Nan::RangeError() - Nan::ReferenceError() - Nan::SyntaxError() - Nan::TypeError() - Nan::ThrowError() - Nan::ThrowRangeError() - Nan::ThrowReferenceError() - Nan::ThrowSyntaxError() - Nan::ThrowTypeError() - Nan::FatalException() - Nan::ErrnoException() - Nan::TryCatch ### Buffers NAN's `node::Buffer` helpers exist as the API has changed across supported Node versions. Use these methods to ensure compatibility. - Nan::NewBuffer() - Nan::CopyBuffer() - Nan::FreeCallback() ### Nan::Callback `Nan::Callback` makes it easier to use `v8::Function` handles as callbacks. A class that wraps a `v8::Function` handle, protecting it from garbage collection and making it particularly useful for storage and use across asynchronous execution. - Nan::Callback ### Asynchronous work helpers `Nan::AsyncWorker` and `Nan::AsyncProgressWorker` are helper classes that make working with asynchronous code easier. - Nan::AsyncWorker - Nan::AsyncProgressWorkerBase & Nan::AsyncProgressWorker - Nan::AsyncQueueWorker ### Strings & Bytes Miscellaneous string & byte encoding and decoding functionality provided for compatibility across supported versions of V8 and Node. Implemented by NAN to ensure that all encoding types are supported, even for older versions of Node where they are missing. - Nan::Encoding - Nan::Encode() - Nan::DecodeBytes() - Nan::DecodeWrite() ### Object Wrappers The `ObjectWrap` class can be used to make wrapped C++ objects and a factory of wrapped objects. - Nan::ObjectWrap ### V8 internals The hooks to access V8 internals—including GC and statistics—are different across the supported versions of V8, therefore NAN provides its own hooks that call the appropriate V8 methods. - NAN_GC_CALLBACK() - Nan::AddGCEpilogueCallback() - Nan::RemoveGCEpilogueCallback() - Nan::AddGCPrologueCallback() - Nan::RemoveGCPrologueCallback() - Nan::GetHeapStatistics() - Nan::SetCounterFunction() - Nan::SetCreateHistogramFunction() - Nan::SetAddHistogramSampleFunction() - Nan::IdleNotification() - Nan::LowMemoryNotification() - Nan::ContextDisposedNotification() - Nan::GetInternalFieldPointer() - Nan::SetInternalFieldPointer() - Nan::AdjustExternalMemory() ### Miscellaneous V8 Helpers - Nan::Utf8String - Nan::GetCurrentContext() - Nan::SetIsolateData() - Nan::GetIsolateData() - Nan::TypedArrayContents ### Miscellaneous Node Helpers - Nan::MakeCallback() - NAN_MODULE_INIT() - Nan::Export() ### Tests To run the NAN tests do: ``` sh npm install npm run-script rebuild-tests npm test ``` Or just: ``` sh npm install make test ``` ## Governance & Contributing NAN is governed by the [io.js](https://iojs.org/) Addon API Working Group ### Addon API Working Group (WG) The NAN project is jointly governed by a Working Group which is responsible for high-level guidance of the project. Members of the WG are also known as Collaborators, there is no distinction between the two, unlike other io.js projects. The WG has final authority over this project including: * Technical direction * Project governance and process (including this policy) * Contribution policy * GitHub repository hosting * Maintaining the list of additional Collaborators For the current list of WG members, see the project [README.md](./README.md#collaborators). Individuals making significant and valuable contributions are made members of the WG and given commit-access to the project. These individuals are identified by the WG and their addition to the WG is discussed via GitHub and requires unanimous consensus amongst those WG members participating in the discussion with a quorum of 50% of WG members required for acceptance of the vote. _Note:_ If you make a significant contribution and are not considered for commit-access log an issue or contact a WG member directly. For the current list of WG members / Collaborators, see the project [README.md](./README.md#collaborators). ### Consensus Seeking Process The WG follows a [Consensus Seeking](http://en.wikipedia.org/wiki/Consensus-seeking_decision-making) decision making model. Modifications of the contents of the NAN repository are made on a collaborative basis. Anybody with a GitHub account may propose a modification via pull request and it will be considered by the WG. All pull requests must be reviewed and accepted by a WG member with sufficient expertise who is able to take full responsibility for the change. In the case of pull requests proposed by an existing WG member, an additional WG member is required for sign-off. Consensus should be sought if additional WG members participate and there is disagreement around a particular modification. If a change proposal cannot reach a consensus, a WG member can call for a vote amongst the members of the WG. Simple majority wins. ## Developer's Certificate of Origin 1.1 By making a contribution to this project, I certify that: * (a) The contribution was created in whole or in part by me and I have the right to submit it under the open source license indicated in the file; or * (b) The contribution is based upon previous work that, to the best of my knowledge, is covered under an appropriate open source license and I have the right under that license to submit that work with modifications, whether created in whole or in part by me, under the same open source license (unless I am permitted to submit under a different license), as indicated in the file; or * (c) The contribution was provided directly to me by some other person who certified (a), (b) or (c) and I have not modified it. * (d) I understand and agree that this project and the contribution are public and that a record of the contribution (including all personal information I submit with it, including my sign-off) is maintained indefinitely and may be redistributed consistent with this project or the open source license(s) involved. ### WG Members / Collaborators
Rod VaggGitHub/rvaggTwitter/@rvagg
Benjamin ByholmGitHub/kkoopa-
Trevor NorrisGitHub/trevnorrisTwitter/@trevnorris
Nathan RajlichGitHub/TooTallNateTwitter/@TooTallNate
Brett LawsonGitHub/brett19Twitter/@brett19x
Ben NoordhuisGitHub/bnoordhuisTwitter/@bnoordhuis
David SiegelGitHub/agnatTwitter/@agnat
## Licence & copyright Copyright (c) 2016 NAN WG Members / Collaborators (listed above). Native Abstractions for Node.js is licensed under an MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE file for more details.