SlideShare a Scribd company logo
Node.js Native AddOns from zero to hero
Nicola Del Gobbo
ROME - APRIL 13/14 2018
Developer
N-API TEAM
Who is Nicola Del Gobbo?
What is Node.js Native Add-on?
C / C++ code called from JavaScript
BRIDGE
Native environment JavaScript
From Node.js documentation
Node.js Addons are dynamically-linked shared objects, written in
C++, that can be loaded into Node.js using the require() function,
and used just as if they were an ordinary Node.js module.
They are used primarily to provide an interface between JavaScript
running in Node.js and C/C++ libraries.
How is it possible?
All the magic is behind the Node.js architecture
Why?
Performance
In general C / C++ code performs better than
JavaScript code, but it’s not always true.
Image processing (in average 6 times faster)
Video processing
CRC cyclic redundancy check (in average 125 times faster)
Compression
Scientific calculus
Algorithms that execute CPU heavy tasks
Why?
Integrate legacy application
You have the source code of an old C / C++ application
and want to expose something of its functionalities
Why?
You don’t find what fits your specific needs on npm
Sometimes completely implementing the module
in JavaScript is not the right solution
Think at libraries like:
ImageMagick
Ghostscript
FFmpeg
TensorFlow
…
Why?
Better error handling
Even if you will use an old C / C++ library you will get an
error code that explains the error that just happened
In new C / C++ library you have the exception
You don’t have to parse some string to identify if there
was an error and what kind of it
With great power comes great responsibility
Ben Parker
Problems
Fragmentation API
The API to implement native add-ons has been changed across
different version of Node.js
Most of the changes were on V8 API and ObjectWrap API
0.8 - 0.10.x - 0.12.x - 1.x - 2.x - 3.x - 4.x - 5.x - 6.x - 7.x - 8.x - 9.x
For more info http://v8docs.nodesource.com/
Problems
Need an adapter to stay compatible across different
version of Node.js
• NAN - Native Abstraction for Node.js
• API compatibility
• Strong bonded with V8 API
• You have to recompile your native add-ons switching to
different version of Node.js
Problems
End user
Mantainers
Problems
Write portable C / C++ code
Your native code must compile and run on different:
ARCHITECTURE PLATFORM COMPILER
Problems
Documentation
• C / C++ libraries that you are integrating are not well documented
• There are good references but not so much practical guide
focusing on complex concepts about native add-ons
N-API
N-API will be a game changer on the native add-on
development
• API and ABI compatibility
• Isolated from V8 (VM agnostic)
• New ES6 types
• C / C++ (only header wrapper)
• Conversion tool that helps to migrate from NAN
• Generator (helps with initial scaffolding)
• Pre-builds (node-pre-gyp - prebuildify)
How to organize your project
Example: the JavaScript part
Example: the JavaScript part
Example: the binding.gyp
Example: the C / C++ part
See the example here
https://github.com/NickNaso/conf-cd-rome-2018/tree/master/00-echo
Asynchronous code
Asynchronous code
See the example here
https://github.com/NickNaso/conf-cd-rome-2018/tree/master/01-pass-
function
Asynchronous code
Preserve reference to function we want call
Create worker threads using libuv
Handle the results
AsyncWorker
AsyncWorker
See the example here
https://github.com/NickNaso/conf-cd-rome-2018/tree/master/02-async-
worker
AsyncWorker
You cannot call JavaScript function from the Worker Thread
until this PR will be landed
• ObjectWrap is a way to expose your C++ code to JavaScript
• You have to extend ObjectWrap class that includes the plumbing to
connect JavaScript code to a C++ object
• Classes extending ObjectWrap can be instantiated from JavaScript
using the new operator, and their methods can be directly invoked
from JavaScript
• Unfortunately, the wrap part really refers to a way to group methods and
state
• It’s your responsibility write custom code to bridge each of your C++
class methods.
ObjectWrap API
Much of the Node.js core API modules are built aroud an idiomatic asynchronous
event-driven architecture in which certains kinds of objects (called emitter)
periodically emit named events that cause Function objects ("listeners") to be
called.
• Emit event from C++
• Implement a native add-on object that inherits from Event Emitter
Event Emitter
See the example here
https://github.com/NickNaso/conf-cd-rome-2018/tree/master/04-addon-
event-emitter
A stream is an abstract interface for working with streaming data in Node.js.
The stream module provides a base API that makes it easy to build objects
that implement the stream interface.
Using Transform stream to pass and get back data from a native add-on
Stream
See the example here
https://github.com/NickNaso/conf-cd-rome-2018/tree/master/05-addon-
stream
• Create simple interface between C / C++ and JavaScript
• Think carefully at JavaScript interface
• Use ObjectWrap API to return C / C++ object to JavaScript
• Validate the types on the native side
• Expose only the functionalities you need
• Don’t block the event loop, stay asynchronous: this is a
must if you will use the add-ons in high performance services
• Use Buffer to pass big quantity of data
Lessons learned
• The largest number of native add-ons is written using NAN
• N-API will be go out of experimental very soon
• Backports for 8.x
• Backports for 6.x
• Documentation for node-addon-api
• Porting preexistentes native addon-ons to N-API
• Investigate how to use prebuild with N-API
Present and future
Implement key value database
Binding to Vedis an embeddable datastore C library
Thanks!
https://github.com/NickNaso/conf-cd-rome-2018
All examples and materials are here
Don’t be afraid sometimes it’s a good thing dirty your hands
with a little of C++
nicoladelgobbo@gmail.com
@NickNaso on Twitter

More Related Content

PDF
Node.js Native AddOns from zero to hero - Nicola Del Gobbo - Codemotion Rome ...
PPTX
Node js with steroids
PPTX
Nativescript with angular 2
PDF
JS Fest 2019/Autumn. Алексей Орленко. Node.js N-API for Rust
PDF
Everything-as-code. A polyglot adventure. #DevoxxPL
PPTX
Next Generation N-API
PDF
Cicd pixelfederation
PDF
CMPE 297 Lecture: Building Infrastructure Clouds with OpenStack
Node.js Native AddOns from zero to hero - Nicola Del Gobbo - Codemotion Rome ...
Node js with steroids
Nativescript with angular 2
JS Fest 2019/Autumn. Алексей Орленко. Node.js N-API for Rust
Everything-as-code. A polyglot adventure. #DevoxxPL
Next Generation N-API
Cicd pixelfederation
CMPE 297 Lecture: Building Infrastructure Clouds with OpenStack

What's hot (20)

PPTX
K8s from Zero to ~Hero~ Seasoned Beginner
PPTX
N api - node interactive 2017
PPTX
Mini .net conf 2020
PDF
How to build a tool for operating Flink on Kubernetes
PDF
API Design in the Modern Era - Architecture Next 2020
PPTX
Infrastrucutre as Code
PDF
Running AWS Locally
PPTX
C++ on the Web: Run your big 3D game in the browser
PDF
Sailing into 2018 with Kubernetes and Istio
PDF
2016 07 - CloudBridge Python library (XSEDE16)
PPTX
Migrating .NET Application to .NET Core
PPTX
DevNetCreate Workshop - build a react app - React crash course
PPTX
N-API NodeSummit-2017
PDF
N api-node summit-2017-final
PPTX
.NET Core: a new .NET Platform
PDF
Building Translate on Glass
PPTX
Helm at reddit: from local dev, staging, to production
PDF
High Productivity Web Development Workflow
PPTX
Gabriele Provinciali/Gabriele Folchi/Luca Postacchini - Sviluppo con piattafo...
PPTX
Net core
K8s from Zero to ~Hero~ Seasoned Beginner
N api - node interactive 2017
Mini .net conf 2020
How to build a tool for operating Flink on Kubernetes
API Design in the Modern Era - Architecture Next 2020
Infrastrucutre as Code
Running AWS Locally
C++ on the Web: Run your big 3D game in the browser
Sailing into 2018 with Kubernetes and Istio
2016 07 - CloudBridge Python library (XSEDE16)
Migrating .NET Application to .NET Core
DevNetCreate Workshop - build a react app - React crash course
N-API NodeSummit-2017
N api-node summit-2017-final
.NET Core: a new .NET Platform
Building Translate on Glass
Helm at reddit: from local dev, staging, to production
High Productivity Web Development Workflow
Gabriele Provinciali/Gabriele Folchi/Luca Postacchini - Sviluppo con piattafo...
Net core
Ad

Similar to Nodejs Native Add-Ons from zero to hero (20)

PPTX
Nodejs overview
PPTX
Getting started with Emscripten – Transpiling C / C++ to JavaScript / HTML5
PPTX
Confoo - Javascript Server Side : How to start
PPTX
Beginners Node.js
PPTX
Best of Microsoft Dev Camp 2015
PPT
Node js
PPTX
React Native new architecture Power Point
PDF
Deno Crate Organization
PDF
Developing realtime apps with Drupal and NodeJS
PPTX
Exploring Next Generation Buildpacks - Anand Rao & Scott Deeg
PDF
I Just Want to Run My Code: Waypoint, Nomad, and Other Things
PDF
4. RTFM, 나는프로그래머다 Meetup 2016 / 한국마이크로소프트 김명신 기술 에반젤리스트
PPTX
Welcome to the microsoft madness
KEY
20120306 dublin js
PPT
Auto cad 2006_api_overview
KEY
20120802 timisoara
PPTX
Advance Android Application Development
PPTX
Introduction to React Native
PDF
Developer-Friendly CI / CD for Kubernetes
PPTX
Angular on ASP.NET MVC 6
Nodejs overview
Getting started with Emscripten – Transpiling C / C++ to JavaScript / HTML5
Confoo - Javascript Server Side : How to start
Beginners Node.js
Best of Microsoft Dev Camp 2015
Node js
React Native new architecture Power Point
Deno Crate Organization
Developing realtime apps with Drupal and NodeJS
Exploring Next Generation Buildpacks - Anand Rao & Scott Deeg
I Just Want to Run My Code: Waypoint, Nomad, and Other Things
4. RTFM, 나는프로그래머다 Meetup 2016 / 한국마이크로소프트 김명신 기술 에반젤리스트
Welcome to the microsoft madness
20120306 dublin js
Auto cad 2006_api_overview
20120802 timisoara
Advance Android Application Development
Introduction to React Native
Developer-Friendly CI / CD for Kubernetes
Angular on ASP.NET MVC 6
Ad

More from Nicola Del Gobbo (6)

PPTX
Nodejs from zero to hero
PPTX
Expressjs from-zero-to-hero
PPTX
Introduzione a Node.js
PPTX
Lexgenda Documenti d’archivio e nuove tecnologie
PPTX
Automatic generation of inspection checklist by user profiling
PPTX
Nodejs from zero to hero
Expressjs from-zero-to-hero
Introduzione a Node.js
Lexgenda Documenti d’archivio e nuove tecnologie
Automatic generation of inspection checklist by user profiling

Recently uploaded (20)

PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
Understanding Forklifts - TECH EHS Solution
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
top salesforce developer skills in 2025.pdf
PDF
Digital Strategies for Manufacturing Companies
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PPTX
Operating system designcfffgfgggggggvggggggggg
PPTX
history of c programming in notes for students .pptx
PDF
Design an Analysis of Algorithms II-SECS-1021-03
PPTX
L1 - Introduction to python Backend.pptx
PDF
medical staffing services at VALiNTRY
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PPTX
Essential Infomation Tech presentation.pptx
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PDF
Softaken Excel to vCard Converter Software.pdf
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Understanding Forklifts - TECH EHS Solution
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
top salesforce developer skills in 2025.pdf
Digital Strategies for Manufacturing Companies
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
Operating system designcfffgfgggggggvggggggggg
history of c programming in notes for students .pptx
Design an Analysis of Algorithms II-SECS-1021-03
L1 - Introduction to python Backend.pptx
medical staffing services at VALiNTRY
PTS Company Brochure 2025 (1).pdf.......
Design an Analysis of Algorithms I-SECS-1021-03
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
Essential Infomation Tech presentation.pptx
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Upgrade and Innovation Strategies for SAP ERP Customers
How to Choose the Right IT Partner for Your Business in Malaysia
Softaken Excel to vCard Converter Software.pdf

Nodejs Native Add-Ons from zero to hero

  • 1. Node.js Native AddOns from zero to hero Nicola Del Gobbo ROME - APRIL 13/14 2018
  • 2. Developer N-API TEAM Who is Nicola Del Gobbo?
  • 3. What is Node.js Native Add-on? C / C++ code called from JavaScript BRIDGE Native environment JavaScript
  • 4. From Node.js documentation Node.js Addons are dynamically-linked shared objects, written in C++, that can be loaded into Node.js using the require() function, and used just as if they were an ordinary Node.js module. They are used primarily to provide an interface between JavaScript running in Node.js and C/C++ libraries.
  • 5. How is it possible? All the magic is behind the Node.js architecture
  • 6. Why? Performance In general C / C++ code performs better than JavaScript code, but it’s not always true. Image processing (in average 6 times faster) Video processing CRC cyclic redundancy check (in average 125 times faster) Compression Scientific calculus Algorithms that execute CPU heavy tasks
  • 7. Why? Integrate legacy application You have the source code of an old C / C++ application and want to expose something of its functionalities
  • 8. Why? You don’t find what fits your specific needs on npm Sometimes completely implementing the module in JavaScript is not the right solution Think at libraries like: ImageMagick Ghostscript FFmpeg TensorFlow …
  • 9. Why? Better error handling Even if you will use an old C / C++ library you will get an error code that explains the error that just happened In new C / C++ library you have the exception You don’t have to parse some string to identify if there was an error and what kind of it
  • 10. With great power comes great responsibility Ben Parker
  • 11. Problems Fragmentation API The API to implement native add-ons has been changed across different version of Node.js Most of the changes were on V8 API and ObjectWrap API 0.8 - 0.10.x - 0.12.x - 1.x - 2.x - 3.x - 4.x - 5.x - 6.x - 7.x - 8.x - 9.x For more info http://v8docs.nodesource.com/
  • 12. Problems Need an adapter to stay compatible across different version of Node.js • NAN - Native Abstraction for Node.js • API compatibility • Strong bonded with V8 API • You have to recompile your native add-ons switching to different version of Node.js
  • 14. Problems Write portable C / C++ code Your native code must compile and run on different: ARCHITECTURE PLATFORM COMPILER
  • 15. Problems Documentation • C / C++ libraries that you are integrating are not well documented • There are good references but not so much practical guide focusing on complex concepts about native add-ons
  • 16. N-API N-API will be a game changer on the native add-on development • API and ABI compatibility • Isolated from V8 (VM agnostic) • New ES6 types • C / C++ (only header wrapper) • Conversion tool that helps to migrate from NAN • Generator (helps with initial scaffolding) • Pre-builds (node-pre-gyp - prebuildify)
  • 17. How to organize your project
  • 21. Example: the C / C++ part
  • 22. See the example here https://github.com/NickNaso/conf-cd-rome-2018/tree/master/00-echo
  • 25. See the example here https://github.com/NickNaso/conf-cd-rome-2018/tree/master/01-pass- function
  • 26. Asynchronous code Preserve reference to function we want call Create worker threads using libuv Handle the results
  • 29. See the example here https://github.com/NickNaso/conf-cd-rome-2018/tree/master/02-async- worker
  • 30. AsyncWorker You cannot call JavaScript function from the Worker Thread until this PR will be landed
  • 31. • ObjectWrap is a way to expose your C++ code to JavaScript • You have to extend ObjectWrap class that includes the plumbing to connect JavaScript code to a C++ object • Classes extending ObjectWrap can be instantiated from JavaScript using the new operator, and their methods can be directly invoked from JavaScript • Unfortunately, the wrap part really refers to a way to group methods and state • It’s your responsibility write custom code to bridge each of your C++ class methods. ObjectWrap API
  • 32. Much of the Node.js core API modules are built aroud an idiomatic asynchronous event-driven architecture in which certains kinds of objects (called emitter) periodically emit named events that cause Function objects ("listeners") to be called. • Emit event from C++ • Implement a native add-on object that inherits from Event Emitter Event Emitter
  • 33. See the example here https://github.com/NickNaso/conf-cd-rome-2018/tree/master/04-addon- event-emitter
  • 34. A stream is an abstract interface for working with streaming data in Node.js. The stream module provides a base API that makes it easy to build objects that implement the stream interface. Using Transform stream to pass and get back data from a native add-on Stream
  • 35. See the example here https://github.com/NickNaso/conf-cd-rome-2018/tree/master/05-addon- stream
  • 36. • Create simple interface between C / C++ and JavaScript • Think carefully at JavaScript interface • Use ObjectWrap API to return C / C++ object to JavaScript • Validate the types on the native side • Expose only the functionalities you need • Don’t block the event loop, stay asynchronous: this is a must if you will use the add-ons in high performance services • Use Buffer to pass big quantity of data Lessons learned
  • 37. • The largest number of native add-ons is written using NAN • N-API will be go out of experimental very soon • Backports for 8.x • Backports for 6.x • Documentation for node-addon-api • Porting preexistentes native addon-ons to N-API • Investigate how to use prebuild with N-API Present and future
  • 38. Implement key value database Binding to Vedis an embeddable datastore C library
  • 39. Thanks! https://github.com/NickNaso/conf-cd-rome-2018 All examples and materials are here Don’t be afraid sometimes it’s a good thing dirty your hands with a little of C++ nicoladelgobbo@gmail.com @NickNaso on Twitter

Editor's Notes

  • #2: Good afternoon everyone. Thank you to attend my talk, today I’m very honored to be here and share my ideas with all of you.
  • #3: My name is Nicola Del Gobbo and I’m developer at Packly. In my every day work I take care of building Packly’s backend systems. In my spare time I try to give my contribution to all frameworks, libraries and modules that I use in my work and obviously I like creating new one. Today the talk is focused on Node.js native addon start with its definition.
  • #4: In a very simple way Native Addons could be considered as C / C++ code called from JavaScript. They are a bridge between our Application programming language JavaScript and Native environment that is completely written in C / C++. This allow us to call C / C++ functions and methods directly from JavaScript.
  • #5: If we take a look at Node.js documentation under Addons section Native Addons are defined as: dynamically-linked shared objects, written in C++, that can be loaded into Node.js using the require() function, and used just as if they were an ordinary Node.js module Their main purpose is to provide an interface between JavaScript running in Node.js and C / C++ libraries. This increase the developer experience because if you are using a Native Addon you don’t care of this, but you just use it as any other pure JavaScript module.
  • #6: How is it possible? All the magic is behind the Node.js architecture. Node.js is built on some C / C++ libraries the most important for us as native addon developers are V8 and libuv. V8 is a JavaScript engine that take care to compile JavaScript code, execute it and give us great performance. Through the V8 APIs we can create function, object and do almost everything that we do on the JavaScript side. Libuv is a high performance evented I/O library and has the responsibility to handle the event loop (our main thread) and all the asynchronous tasks.
  • #7: Why should you implement new Native Add-On? The first reason is for performance In general C / C++ code performs better then JavaScript code, but it’s really true for CPU bounds operations. Think for example at: Image processing | Video processing | Compression | Scientific calculus | Cyclic redundancy check and all algorithms that at one point execute some CPU heavy tasks. In all these cases you can gain more in performance.
  • #8: Sometimes you want just integrate a legacy application So you have the source code of an old C / C++ application and want to expose something of its functionalities through new Node.js application
  • #9: Even if npm is a very large repo where you can find almost everything sometimes you don’t find what fits your specific needs and in this case you have to take a choice. Completely reimplementing the module in JavaScript, but in my opinion it’s an insane idea to reimplement from the ground solutions like ImageMagick | Ghostscript | Ffmpeg and TensorFlow because you will lose all your time on develop a module and not to concentrate on business logic of your application. In these cases the You have to concentrate on business logic of your application and not on developing a single module
  • #17: N-API is one of the most important features announced with Node.js 8 which is aimed at reducing the maintenance cost for native add-ons
  • #18: When I start to develop a new native addon I use the boilerplate depicted on the slide. Here the most important elements are the SRC and LIB folders. SRC folder contains the C / C++ code and the native dependencies while the LIB folder contains the JavaScript code There are also the usual package.json file and the binging.gyp file that contains all the building configurations for the addon. At the end our addon will be composed by two parts one written in C++ and another written in JavaScript and usually the JavaScript part will use the native code to expose some features
  • #19: When I start to develop a new native addon I use the boilerplate depicted on the slide. Here the most important elements are the SRC and LIB folders. SRC folder contains the C / C++ code and the native dependencies while the LIB folder contains the JavaScript code There are also the usual package.json file and the binging.gyp file that contains all the building configurations for the addon. At the end our addon will be composed by two parts one written in C++ and another written in JavaScript and usually the JavaScript part will use the native code to expose some features
  • #20: When I start to develop a new native addon I use the boilerplate depicted on the slide. Here the most important elements are the SRC and LIB folders. SRC folder contains the C / C++ code and the native dependencies while the LIB folder contains the JavaScript code There are also the usual package.json file and the binging.gyp file that contains all the building configurations for the addon. At the end our addon will be composed by two parts one written in C++ and another written in JavaScript and usually the JavaScript part will use the native code to expose some features
  • #21: In our binding.gyp we need to set the target name that will match the module name. The reported example is almost simple sometimes finding the right settings for binding.gyp is not easy so I suggest to take a look at GYP documentation or at nodey-gyp wiki where there are examples of existing binding.gyp and use them as source of inspiration to solve your problems with these kind of configurations.
  • #22: What happen here? The macro NODE_API_MODULE creates code that will register a module named ”echo” and in addition it will ensure that a function init is called when the module is required. In the init we export our function or object. In the reported example we export echo and you can find the code executed by this function in the method Echo. As first thing we validate the input data, then transfer the JavaScript input to C++ data structure. C++ code perform the requested computation and before returning transfer the output data to JavaScript context. This is the most straightforward integration pattern that you can realize to pass data between JavaScript and C / C++ . The main reason for using this approach is simplicity and because you can integrate the C++ without modification. In addition we have a complete decoupling of the JavaScript and C++ code.
  • #25: In an asynchronous addon function, the calling JavaScript code returns immediately. The calling code passes a callback function to the addon, and the addon does its work in a separate worker thread. This avoids locking up the Node.js event loop, as the addon function does not block.