SlideShare a Scribd company logo
1 of 39
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

What's hot

K8s from Zero to ~Hero~ Seasoned Beginner
K8s from Zero to ~Hero~ Seasoned BeginnerK8s from Zero to ~Hero~ Seasoned Beginner
K8s from Zero to ~Hero~ Seasoned BeginnerKristof Jozsa
 
N api - node interactive 2017
N api - node interactive 2017N api - node interactive 2017
N api - node interactive 2017Michael Dawson
 
How to build a tool for operating Flink on Kubernetes
How to build a tool for operating Flink on KubernetesHow to build a tool for operating Flink on Kubernetes
How to build a tool for operating Flink on KubernetesAndreaMedeghini
 
API Design in the Modern Era - Architecture Next 2020
API Design in the Modern Era - Architecture Next 2020API Design in the Modern Era - Architecture Next 2020
API Design in the Modern Era - Architecture Next 2020Eran Stiller
 
Infrastrucutre as Code
Infrastrucutre as CodeInfrastrucutre as Code
Infrastrucutre as CodeHarmeet Singh
 
C++ on the Web: Run your big 3D game in the browser
C++ on the Web: Run your big 3D game in the browserC++ on the Web: Run your big 3D game in the browser
C++ on the Web: Run your big 3D game in the browserAndre Weissflog
 
Sailing into 2018 with Kubernetes and Istio
Sailing into 2018 with Kubernetes and IstioSailing into 2018 with Kubernetes and Istio
Sailing into 2018 with Kubernetes and IstioFernand Galiana
 
2016 07 - CloudBridge Python library (XSEDE16)
2016 07 - CloudBridge Python library (XSEDE16)2016 07 - CloudBridge Python library (XSEDE16)
2016 07 - CloudBridge Python library (XSEDE16)Enis Afgan
 
Migrating .NET Application to .NET Core
Migrating .NET Application to .NET CoreMigrating .NET Application to .NET Core
Migrating .NET Application to .NET CoreBaris Ceviz
 
DevNetCreate Workshop - build a react app - React crash course
DevNetCreate Workshop - build a react app - React crash courseDevNetCreate Workshop - build a react app - React crash course
DevNetCreate Workshop - build a react app - React crash courseCisco DevNet
 
N api-node summit-2017-final
N api-node summit-2017-finalN api-node summit-2017-final
N api-node summit-2017-finalMichael Dawson
 
.NET Core: a new .NET Platform
.NET Core: a new .NET Platform.NET Core: a new .NET Platform
.NET Core: a new .NET PlatformAlex Thissen
 
Building Translate on Glass
Building Translate on GlassBuilding Translate on Glass
Building Translate on GlassTrish Whetzel
 
Helm at reddit: from local dev, staging, to production
Helm at reddit: from local dev, staging, to productionHelm at reddit: from local dev, staging, to production
Helm at reddit: from local dev, staging, to productionGregory Taylor
 
High Productivity Web Development Workflow
High Productivity Web Development WorkflowHigh Productivity Web Development Workflow
High Productivity Web Development WorkflowVũ Nguyễn
 
Gabriele Provinciali/Gabriele Folchi/Luca Postacchini - Sviluppo con piattafo...
Gabriele Provinciali/Gabriele Folchi/Luca Postacchini - Sviluppo con piattafo...Gabriele Provinciali/Gabriele Folchi/Luca Postacchini - Sviluppo con piattafo...
Gabriele Provinciali/Gabriele Folchi/Luca Postacchini - Sviluppo con piattafo...Codemotion
 

What's hot (20)

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

Similar to Nodejs Native Add-Ons from zero to hero

Getting started with Emscripten – Transpiling C / C++ to JavaScript / HTML5
Getting started with Emscripten – Transpiling C / C++ to JavaScript / HTML5Getting started with Emscripten – Transpiling C / C++ to JavaScript / HTML5
Getting started with Emscripten – Transpiling C / C++ to JavaScript / HTML5David Voyles
 
Confoo - Javascript Server Side : How to start
Confoo - Javascript Server Side : How to startConfoo - Javascript Server Side : How to start
Confoo - Javascript Server Side : How to startQuentin Adam
 
Best of Microsoft Dev Camp 2015
Best of Microsoft Dev Camp 2015Best of Microsoft Dev Camp 2015
Best of Microsoft Dev Camp 2015Bluegrass Digital
 
Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS drupalcampest
 
Exploring Next Generation Buildpacks - Anand Rao & Scott Deeg
Exploring Next Generation Buildpacks - Anand Rao & Scott DeegExploring Next Generation Buildpacks - Anand Rao & Scott Deeg
Exploring Next Generation Buildpacks - Anand Rao & Scott DeegVMware Tanzu
 
I Just Want to Run My Code: Waypoint, Nomad, and Other Things
I Just Want to Run My Code: Waypoint, Nomad, and Other ThingsI Just Want to Run My Code: Waypoint, Nomad, and Other Things
I Just Want to Run My Code: Waypoint, Nomad, and Other ThingsMichael Lange
 
4. RTFM, 나는프로그래머다 Meetup 2016 / 한국마이크로소프트 김명신 기술 에반젤리스트
4. RTFM, 나는프로그래머다 Meetup 2016 / 한국마이크로소프트 김명신 기술 에반젤리스트 4. RTFM, 나는프로그래머다 Meetup 2016 / 한국마이크로소프트 김명신 기술 에반젤리스트
4. RTFM, 나는프로그래머다 Meetup 2016 / 한국마이크로소프트 김명신 기술 에반젤리스트 양 한빛
 
Welcome to the microsoft madness
Welcome to the microsoft madnessWelcome to the microsoft madness
Welcome to the microsoft madness명신 김
 
Auto cad 2006_api_overview
Auto cad 2006_api_overviewAuto cad 2006_api_overview
Auto cad 2006_api_overviewscdhruv5
 
Announcing AWS CodeBuild - January 2017 Online Teck Talks
Announcing AWS CodeBuild - January 2017 Online Teck TalksAnnouncing AWS CodeBuild - January 2017 Online Teck Talks
Announcing AWS CodeBuild - January 2017 Online Teck TalksAmazon Web Services
 
Advance Android Application Development
Advance Android Application DevelopmentAdvance Android Application Development
Advance Android Application DevelopmentRamesh Prasad
 
Introduction to React Native
Introduction to React NativeIntroduction to React Native
Introduction to React NativeWaqqas Jabbar
 
Developer-Friendly CI / CD for Kubernetes
Developer-Friendly CI / CD for KubernetesDeveloper-Friendly CI / CD for Kubernetes
Developer-Friendly CI / CD for KubernetesDevOps Indonesia
 
Angular on ASP.NET MVC 6
Angular on ASP.NET MVC 6Angular on ASP.NET MVC 6
Angular on ASP.NET MVC 6Noam Kfir
 

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

Nodejs overview
Nodejs overviewNodejs overview
Nodejs overview
 
Getting started with Emscripten – Transpiling C / C++ to JavaScript / HTML5
Getting started with Emscripten – Transpiling C / C++ to JavaScript / HTML5Getting started with Emscripten – Transpiling C / C++ to JavaScript / HTML5
Getting started with Emscripten – Transpiling C / C++ to JavaScript / HTML5
 
Confoo - Javascript Server Side : How to start
Confoo - Javascript Server Side : How to startConfoo - Javascript Server Side : How to start
Confoo - Javascript Server Side : How to start
 
Beginners Node.js
Beginners Node.jsBeginners Node.js
Beginners Node.js
 
Best of Microsoft Dev Camp 2015
Best of Microsoft Dev Camp 2015Best of Microsoft Dev Camp 2015
Best of Microsoft Dev Camp 2015
 
Node js
Node jsNode js
Node js
 
Deno Crate Organization
Deno Crate OrganizationDeno Crate Organization
Deno Crate Organization
 
Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS Developing realtime apps with Drupal and NodeJS
Developing realtime apps with Drupal and NodeJS
 
Exploring Next Generation Buildpacks - Anand Rao & Scott Deeg
Exploring Next Generation Buildpacks - Anand Rao & Scott DeegExploring Next Generation Buildpacks - Anand Rao & Scott Deeg
Exploring Next Generation Buildpacks - Anand Rao & Scott Deeg
 
I Just Want to Run My Code: Waypoint, Nomad, and Other Things
I Just Want to Run My Code: Waypoint, Nomad, and Other ThingsI Just Want to Run My Code: Waypoint, Nomad, and Other Things
I Just Want to Run My Code: Waypoint, Nomad, and Other Things
 
4. RTFM, 나는프로그래머다 Meetup 2016 / 한국마이크로소프트 김명신 기술 에반젤리스트
4. RTFM, 나는프로그래머다 Meetup 2016 / 한국마이크로소프트 김명신 기술 에반젤리스트 4. RTFM, 나는프로그래머다 Meetup 2016 / 한국마이크로소프트 김명신 기술 에반젤리스트
4. RTFM, 나는프로그래머다 Meetup 2016 / 한국마이크로소프트 김명신 기술 에반젤리스트
 
Welcome to the microsoft madness
Welcome to the microsoft madnessWelcome to the microsoft madness
Welcome to the microsoft madness
 
20120306 dublin js
20120306 dublin js20120306 dublin js
20120306 dublin js
 
Auto cad 2006_api_overview
Auto cad 2006_api_overviewAuto cad 2006_api_overview
Auto cad 2006_api_overview
 
Announcing AWS CodeBuild - January 2017 Online Teck Talks
Announcing AWS CodeBuild - January 2017 Online Teck TalksAnnouncing AWS CodeBuild - January 2017 Online Teck Talks
Announcing AWS CodeBuild - January 2017 Online Teck Talks
 
20120802 timisoara
20120802 timisoara20120802 timisoara
20120802 timisoara
 
Advance Android Application Development
Advance Android Application DevelopmentAdvance Android Application Development
Advance Android Application Development
 
Introduction to React Native
Introduction to React NativeIntroduction to React Native
Introduction to React Native
 
Developer-Friendly CI / CD for Kubernetes
Developer-Friendly CI / CD for KubernetesDeveloper-Friendly CI / CD for Kubernetes
Developer-Friendly CI / CD for Kubernetes
 
Angular on ASP.NET MVC 6
Angular on ASP.NET MVC 6Angular on ASP.NET MVC 6
Angular on ASP.NET MVC 6
 

More from Nicola Del Gobbo

Expressjs from-zero-to-hero
Expressjs from-zero-to-heroExpressjs from-zero-to-hero
Expressjs from-zero-to-heroNicola Del Gobbo
 
Lexgenda Documenti d’archivio e nuove tecnologie
Lexgenda Documenti d’archivio e nuove tecnologieLexgenda Documenti d’archivio e nuove tecnologie
Lexgenda Documenti d’archivio e nuove tecnologieNicola Del Gobbo
 
Automatic generation of inspection checklist by user profiling
Automatic generation of inspection checklist by user profilingAutomatic generation of inspection checklist by user profiling
Automatic generation of inspection checklist by user profilingNicola Del Gobbo
 

More from Nicola Del Gobbo (6)

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

Recently uploaded

UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 

Recently uploaded (20)

UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 

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

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
  6. 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.
  7. 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
  8. 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
  9. 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
  10. 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
  11. 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
  12. 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
  13. 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.
  14. 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.
  15. 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.