- Notifications
You must be signed in to change notification settings - Fork512
Native Abstractions for Node.js
License
nodejs/nan
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
A header file filled with macro and utility goodness for making add-on development for Node.js easier across versions 8, 10, 12, 14, 16, 17, 18, 19, 20, 21, and 22.
Current version: 2.22.2
(SeeCHANGELOG.md for complete ChangeLog)
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 inspectNODE_MODULE_VERSION
and get yourself into a macro-tangle.
This project also contains some helper utilities that make addon development a bit more pleasant.
Simply addNAN as a dependency in thepackage.json of your Node addon:
$ npm install --save nan
Pull in the path toNAN in yourbinding.gyp so that you can use#include <nan.h>
in your.cpp files:
"include_dirs" : ["<!(node -e\"require('nan')\")"]
This works like a-I<path-to-NAN>
when compiling your addon.
Just getting started with Nan? Take a look at theNode Add-on Examples.
Refer to aquick-startNan Boilerplate for a ready-to-go project that utilizes basic Nan functionality.
For a simpler example, see theasync pi estimation example 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 ofNAN.
Yet another example isnan-example-eol. It shows newline detection implemented as a native addon.
Also take a look at our comprehensiveC++ test suite which has a plethora of code snippets for your pasting pleasure.
Additional to the NAN documentation below, please consult:
Atemplate 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 onTemplates 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-deceasedv8::Argument
type.
- Method argument types
- 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()
Alocal 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 ofHandleScope
objects is different across the supported versions of V8. Therefore, NAN provides its own implementations that can be used safely across these.
Also see the V8 Embedders Guide section onHandles and Garbage Collection.
An object reference that is independent of anyHandleScope
is apersistent reference. Where aLocal
handle only lives as long as theHandleScope
in which it was allocated, aPersistent
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 thePersistent
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 onHandles and Garbage Collection.
NAN provides aNan::New()
helper for the creation of new JavaScript objects in a way that's compatible across the supported versions of V8.
NAN contains functions that convertv8::Value
s to otherv8::Value
types and native types. Since type conversion is not guaranteed to succeed, they returnNan::Maybe
types. These converters can be used in place ofvalue->ToX()
andvalue->XValue()
(whereX
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 newv8::Maybe
andv8::MaybeLocal
types for these conversions, older versions don't have this functionality so it is provided by NAN.
TheNan::MaybeLocal
andNan::Maybe
types are monads that encapsulatev8::Local
handles thatmay be empty.
- Maybe Types
- Maybe Helpers
Nan::Call()
Nan::ToDetailString()
Nan::ToArrayIndex()
Nan::Equals()
Nan::NewInstance()
Nan::GetFunction()
Nan::Set()
Nan::DefineOwnProperty()
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()
NAN providesv8::Script
helpers as the API has changed over the supported versions of V8.
TheJSON object provides the C++ versions of the methods offered by theJSON
object in javascript. V8 exposes these methods via thev8::JSON
object.
Refer to the V8 JSON object in theV8 documentation for more information about these methods and their arguments.
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 ofv8::Value
.
Also consult the V8 Embedders Guide section onExceptions 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
NAN'snode::Buffer
helpers exist as the API has changed across supported Node versions. Use these methods to ensure compatibility.
Nan::Callback
makes it easier to usev8::Function
handles as callbacks. A class that wraps av8::Function
handle, protecting it from garbage collection and making it particularly useful for storage and use across asynchronous execution.
Nan::AsyncWorker
,Nan::AsyncProgressWorker
andNan::AsyncProgressQueueWorker
are helper classes that make working with asynchronous code easier.
Nan::AsyncWorker
Nan::AsyncProgressWorkerBase & Nan::AsyncProgressWorker
Nan::AsyncProgressQueueWorker
Nan::AsyncQueueWorker
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.
TheObjectWrap
class can be used to make wrapped C++ objects and a factory of wrapped objects.
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()
Nan::Utf8String
Nan::GetCurrentContext()
Nan::SetIsolateData()
Nan::GetIsolateData()
Nan::TypedArrayContents
To run the NAN tests do:
npm installnpm run-script rebuild-testsnpmtest
Or just:
npm installmaketest
With new enough compilers available on OSX, the versions of V8 headers corresponding to Node.js 0.12do not compile anymore. The error looks something like:
❯ CXX(target) Release/obj.target/accessors/cpp/accessors.oIn file included from ../cpp/accessors.cpp:9:In file included from ../../nan.h:51:In file included from /Users/ofrobots/.node-gyp/0.12.18/include/node/node.h:61:/Users/ofrobots/.node-gyp/0.12.18/include/node/v8.h:5800:54: error: 'CreateHandle' is a protected member of 'v8::HandleScope' return Handle<T>(reinterpret_cast<T*>(HandleScope::CreateHandle( ~~~~~~~~~~~~~^~~~~~~~~~~~
This can be worked around by patching your local versions of v8.h corresponding to Node 0.12 to makev8::Handle
a friend ofv8::HandleScope
. Since neither Node.js not V8 support this release line anymorethis patch cannot be released by either project in an official release.
For this reason, we do not test against Node.js 0.12 on OSX in this project's CI. If you need to supportthat configuration, you will need to either get an older compiler, or apply a source patch to the versionof V8 headers as a workaround.
NAN is governed by theNode.js Addon API Working Group
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 Node.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 projectREADME.md.
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 projectREADME.md.
The WG follows aConsensus Seeking 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.
By making a contribution to this project, I certify that:
(a) The contribution was created in whole or in part by me and Ihave the right to submit it under the open source licenseindicated in the file; or
(b) The contribution is based upon previous work that, to the bestof my knowledge, is covered under an appropriate open sourcelicense and I have the right under that license to submit thatwork with modifications, whether created in whole or in partby me, under the same open source license (unless I ampermitted to submit under a different license), as indicatedin the file; or
(c) The contribution was provided directly to me by some otherperson who certified (a), (b) or (c) and I have not modifiedit.
(d) I understand and agree that this project and the contributionare public and that a record of the contribution (including allpersonal information I submit with it, including my sign-off) ismaintained indefinitely and may be redistributed consistent withthis project or the open source license(s) involved.
Rod Vagg | GitHub/rvagg | Twitter/@rvagg |
---|---|---|
Benjamin Byholm | GitHub/kkoopa | - |
Trevor Norris | GitHub/trevnorris | Twitter/@trevnorris |
Nathan Rajlich | GitHub/TooTallNate | Twitter/@TooTallNate |
Brett Lawson | GitHub/brett19 | Twitter/@brett19x |
Ben Noordhuis | GitHub/bnoordhuis | Twitter/@bnoordhuis |
David Siegel | GitHub/agnat | Twitter/@agnat |
Michael Ira Krufky | GitHub/mkrufky | Twitter/@mkrufky |
Copyright (c) 2018 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.
About
Native Abstractions for Node.js