Security News
Input Validation Vulnerabilities Dominate MITRE's 2024 CWE Top 25 List
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
The 'nan' package stands for 'Native Abstractions for Node.js'. It is a header file that wraps Node.js and V8 APIs, providing a set of utilities for native module developers to create and maintain native addons across Node.js versions.
Simple Asynchronous Operations
This feature allows developers to perform asynchronous operations in their native addons. The code sample demonstrates how to create an asynchronous worker using 'NanAsyncWorker' and queue it with 'NanAsyncQueueWorker'.
const { NanAsyncWorker, NanAsyncQueueWorker } = require('nan');
class MyWorker extends NanAsyncWorker {
constructor(callback) {
super(callback);
}
Execute() {
// perform heavy task
}
HandleOKCallback() {
this->callback().Call(0, nullptr);
}
}
NanAsyncQueueWorker(new MyWorker(new NanCallback(callback)));
Persistent References
This feature provides a way to create persistent references to V8 objects that won't be garbage collected until explicitly cleared. The code sample shows how to create, reset, check, and clear a persistent reference.
const { NanPersistent } = require('nan');
let persistent = new NanPersistent<v8::Object>();
persistent.Reset(obj); // obj is a V8 object
persistent.IsEmpty(); // checks if the persistent handle is empty
persistent.Clear(); // clears the persistent handle
Callbacks
This feature allows native module developers to store and invoke callbacks. The code sample illustrates how to create a 'NanCallback' from a V8 function and invoke it with no arguments.
const { NanCallback } = require('nan');
let callback = new NanCallback(info[0].As<v8::Function>());
callback.Call(0, nullptr);
node-addon-api is an alternative to 'nan' that provides a C++ wrapper classes which simplify the use of the Node.js Addon API. It aims to provide a more stable API across Node.js versions and is recommended by the Node.js team as the primary interface for writing native addons.
ffi-napi is a Node.js addon for loading and calling dynamic libraries using pure JavaScript. It is similar to 'nan' in that it allows interaction with native code, but it focuses on foreign function interfaces rather than providing abstractions for writing native modules.
ref-napi is a package that provides a way to create, access, and manipulate binary data in Buffer instances in Node.js. It is similar to 'nan' in that it deals with native memory management, but it is more focused on buffer manipulation rather than abstracting Node.js and V8 APIs.
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 and 6.
Current version: 2.3.5
(See CHANGELOG.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 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.
Simply add NAN as a dependency in the package.json of your Node addon:
$ npm install --save nan
Pull in the path to NAN in your binding.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 the Node Add-on Examples.
Refer to a quick-start Nan Boilerplate for a ready-to-go project that utilizes basic Nan functionality.
For a simpler example, see the async 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 of NAN.
Yet another example is nan-example-eol. It shows newline detection implemented as a native addon.
Also take a look at our comprehensive C++ test suite which has a plehora of code snippets for your pasting pleasure.
Additional to the NAN documentation below, please consult:
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 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.
Nan::SetMethod()
Nan::SetPrototypeMethod()
Nan::SetAccessor()
Nan::SetNamedPropertyHandler()
Nan::SetIndexedPropertyHandler()
Nan::SetTemplate()
Nan::SetPrototypeTemplate()
Nan::SetInstanceTemplate()
Nan::SetCallHandler()
Nan::SetCallAsFunctionHandler()
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.
Also see the V8 Embedders Guide section on Handles and Garbage Collection.
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.
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 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.
The Nan::MaybeLocal
and Nan::Maybe
types are monads that encapsulate v8::Local
handles that may be empty.
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::MakeMaybe()
NAN provides a v8::Script
helpers as the API has changed over the supported versions of V8.
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 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's node::Buffer
helpers exist as the API has changed across supported Node versions. Use these methods to ensure compatibility.
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::AsyncWorker
and Nan::AsyncProgressWorker
are helper classes that make working with asynchronous code easier.
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.
The ObjectWrap
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 install
npm run-script rebuild-tests
npm test
Or just:
npm install
make test
NAN is governed by the io.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 io.js projects.
The WG has final authority over this project including:
For the current list of WG members, see the project README.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 project README.md.
The WG follows a Consensus 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 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.
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 | - |
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.
2.3.5 May 31 2016
FAQs
Native Abstractions for Node.js: C++ header for Node 0.8 -> 23 compatibility
The npm package nan receives a total of 16,823,932 weekly downloads. As such, nan popularity was classified as popular.
We found that nan demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.
Research
Security News
A threat actor's playbook for exploiting the npm ecosystem was exposed on the dark web, detailing how to build a blockchain-powered botnet.