SlideShare a Scribd company logo
Node.js With Steroids
Make Better Node.js Application with Native Add-Ons
Nicola Del Gobbo, Developer, Packly
Who is Nicola Del Gobbo?
Developer Contribute to
What is Node.js Native Addon?
In a very simple way Native Addons could be considered as
C / C++ code called from JavaScript
BRIDGE
Native environment JavaScript environment
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 should you implement new Native Add-on?
Performance
In general C / C++ code performs better than JavaScript code, but it’s
really true for CPU bounds operations
• 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 should you implement new Native Add-on?
Integrate legacy application
You have the source code of an old C / C++ application and want to
expose something of its functionalities through the new Node.js
application
Why should you implement new Native Add-on?
You don’t find what fits your specific needs on npm
Sometimes completely reimplementing the module in JavaScript is
not the right solution
Think at libraries like:
• ImageMagick
• Ghostscript
• FFmpeg
• TensorFlow
You have to concentrate on business logic of
your application and not on developing a single
module
Why should you implement new Native Add-on?
Desktop application
You want to use the local underlying CPU or GPU resources to
execute the most complex tasks
Es. Electron or NW.js
• Better performance on the local side
• Better performance on the server
Why should you implement new Native Add-on?
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
Problems
Fragmentation 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
The API to implement Native Add-Ons have been changed across
different version of Node.js
Most of the changes were on V8 API and ObjectWrap API
For more info http://v8docs.nodesource.com/
Problems
Fragmentation API
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
Write portable C / C++ code
At one point your native code must compile 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 concepts about Native Add-Ons
How to organize your native Addon project
src C/C++ code and maybe dependencies
binding.gyp building configurations
lib JavaScript code
package.json
Example: the JavaScript part
Example: the C / C++ part
Example: the binding.gyp
Sometimes finding the right settings for binding.gyp is not easy
Refer to GYP documentation
https://gyp.gsrc.io/docs/UserDocumentation.md
More useful examples to take inspiration from other developers
https://github.com/nodejs/node-gyp/wiki/”binding.gyp”-files-out-in-the-wild
Which kind of Addon should you implement?
TIME: Amount of processing time spent on the C++
code
DATA: Amount of data flowing between C++ and
JavaScript
Async example
Buffer example
ObjectWrap API
• 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 example
Lessons learned from my experience
• Create simple interface between C / C++ and JavaScript
• Insert complexity on the JavaScript side
• 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 Addons on a distributed system
• Use Buffer to pass big quantity of data
• If you have many parameters use JSON to pass and parse data
• Consider the using of protobuf
Present and future
• The largest number of native addons is written using NAN
• NAN helps stay compatible with old versions of Node.js
• N-API will be a game changer on the native addon
development
• ABI compatibility
• New ES6 types
• Isolated from V8 API (VM agnostic)
• C / C++
• Conversion tool that helps to migrate from NAN
• Great developer experience for mantainers
Implement high performance
key value database
Binding to Vedis an embeddable datastore C library
https://github.com/NickNaso/conf-ni-
2017
Thanks!
nicoladelgobbo@gmail.com
@NickNaso on Twitter
All examples and materials are here
https://github.com/NickNaso/conf-ni-
2017

More Related Content

What's hot

Rene Groeschke
Rene GroeschkeRene Groeschke
Rene Groeschke
CodeFest
 
Iguazú: A Long-Running Job Scheduler using Docker and Mesos
Iguazú: A Long-Running Job Scheduler using Docker and MesosIguazú: A Long-Running Job Scheduler using Docker and Mesos
Iguazú: A Long-Running Job Scheduler using Docker and Mesos
Colleen Lee
 
Infrastructure as Code on AWS
Infrastructure as Code on AWSInfrastructure as Code on AWS
Infrastructure as Code on AWS
Bhuvaneswari Subramani
 
Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular
Jalpesh Vadgama
 
Efficient DevOps Tooling with Java and GraalVM
Efficient DevOps Tooling with Java and GraalVMEfficient DevOps Tooling with Java and GraalVM
Efficient DevOps Tooling with Java and GraalVM
QAware GmbH
 
Infrastrucutre as Code
Infrastrucutre as CodeInfrastrucutre as Code
Infrastrucutre as Code
Harmeet Singh
 
From C++ to JS via Emscripten
From C++ to JS via EmscriptenFrom C++ to JS via Emscripten
From C++ to JS via Emscripten
TomNickson
 
Serverless in java Lessons learnt
Serverless in java Lessons learntServerless in java Lessons learnt
Serverless in java Lessons learnt
Krzysztof Pawlowski
 
Technology | Serverless
Technology | ServerlessTechnology | Serverless
Technology | Serverless
Ani Sinanaj
 
Graph ql subscriptions through the looking glass
Graph ql subscriptions through the looking glassGraph ql subscriptions through the looking glass
Graph ql subscriptions through the looking glass
Gerard Klijs
 
Building occasionally connected applications using event sourcing
Building occasionally connected applications using event sourcingBuilding occasionally connected applications using event sourcing
Building occasionally connected applications using event sourcing
Dennis Doomen
 
Alfresco Development Framework Basic
Alfresco Development Framework BasicAlfresco Development Framework Basic
Alfresco Development Framework Basic
Mario Romano
 
Managing short lived Kubernetes (Production) deployments
Managing short lived Kubernetes (Production) deploymentsManaging short lived Kubernetes (Production) deployments
Managing short lived Kubernetes (Production) deployments
Haufe-Lexware GmbH & Co KG
 
Powering machine learning workflows with Apache Airflow and Python
Powering machine learning workflows with Apache Airflow and PythonPowering machine learning workflows with Apache Airflow and Python
Powering machine learning workflows with Apache Airflow and Python
Tatiana Al-Chueyr
 
Everything-as-code. Polyglotte Software-Entwicklung in der Praxis.
Everything-as-code. Polyglotte Software-Entwicklung in der Praxis.Everything-as-code. Polyglotte Software-Entwicklung in der Praxis.
Everything-as-code. Polyglotte Software-Entwicklung in der Praxis.
QAware GmbH
 
Developing Microservices with Apache Camel
Developing Microservices with Apache CamelDeveloping Microservices with Apache Camel
Developing Microservices with Apache Camel
Claus Ibsen
 
Neptue Graph Database - 0 to Production
Neptue Graph Database - 0 to ProductionNeptue Graph Database - 0 to Production
Neptue Graph Database - 0 to Production
israelio
 
Continuous deployment of Rails apps on AWS OpsWorks
Continuous deployment of Rails apps on AWS OpsWorksContinuous deployment of Rails apps on AWS OpsWorks
Continuous deployment of Rails apps on AWS OpsWorks
Tomaž Zaman
 
Aws lambda best practices - ignite - dev opsdays-charlotte
Aws lambda   best practices - ignite - dev opsdays-charlotteAws lambda   best practices - ignite - dev opsdays-charlotte
Aws lambda best practices - ignite - dev opsdays-charlotte
Derek Ashmore
 
Cortex: Prometheus as a Service, One Year On
Cortex: Prometheus as a Service, One Year OnCortex: Prometheus as a Service, One Year On
Cortex: Prometheus as a Service, One Year On
Kausal
 

What's hot (20)

Rene Groeschke
Rene GroeschkeRene Groeschke
Rene Groeschke
 
Iguazú: A Long-Running Job Scheduler using Docker and Mesos
Iguazú: A Long-Running Job Scheduler using Docker and MesosIguazú: A Long-Running Job Scheduler using Docker and Mesos
Iguazú: A Long-Running Job Scheduler using Docker and Mesos
 
Infrastructure as Code on AWS
Infrastructure as Code on AWSInfrastructure as Code on AWS
Infrastructure as Code on AWS
 
Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular Top 10 RxJs Operators in Angular
Top 10 RxJs Operators in Angular
 
Efficient DevOps Tooling with Java and GraalVM
Efficient DevOps Tooling with Java and GraalVMEfficient DevOps Tooling with Java and GraalVM
Efficient DevOps Tooling with Java and GraalVM
 
Infrastrucutre as Code
Infrastrucutre as CodeInfrastrucutre as Code
Infrastrucutre as Code
 
From C++ to JS via Emscripten
From C++ to JS via EmscriptenFrom C++ to JS via Emscripten
From C++ to JS via Emscripten
 
Serverless in java Lessons learnt
Serverless in java Lessons learntServerless in java Lessons learnt
Serverless in java Lessons learnt
 
Technology | Serverless
Technology | ServerlessTechnology | Serverless
Technology | Serverless
 
Graph ql subscriptions through the looking glass
Graph ql subscriptions through the looking glassGraph ql subscriptions through the looking glass
Graph ql subscriptions through the looking glass
 
Building occasionally connected applications using event sourcing
Building occasionally connected applications using event sourcingBuilding occasionally connected applications using event sourcing
Building occasionally connected applications using event sourcing
 
Alfresco Development Framework Basic
Alfresco Development Framework BasicAlfresco Development Framework Basic
Alfresco Development Framework Basic
 
Managing short lived Kubernetes (Production) deployments
Managing short lived Kubernetes (Production) deploymentsManaging short lived Kubernetes (Production) deployments
Managing short lived Kubernetes (Production) deployments
 
Powering machine learning workflows with Apache Airflow and Python
Powering machine learning workflows with Apache Airflow and PythonPowering machine learning workflows with Apache Airflow and Python
Powering machine learning workflows with Apache Airflow and Python
 
Everything-as-code. Polyglotte Software-Entwicklung in der Praxis.
Everything-as-code. Polyglotte Software-Entwicklung in der Praxis.Everything-as-code. Polyglotte Software-Entwicklung in der Praxis.
Everything-as-code. Polyglotte Software-Entwicklung in der Praxis.
 
Developing Microservices with Apache Camel
Developing Microservices with Apache CamelDeveloping Microservices with Apache Camel
Developing Microservices with Apache Camel
 
Neptue Graph Database - 0 to Production
Neptue Graph Database - 0 to ProductionNeptue Graph Database - 0 to Production
Neptue Graph Database - 0 to Production
 
Continuous deployment of Rails apps on AWS OpsWorks
Continuous deployment of Rails apps on AWS OpsWorksContinuous deployment of Rails apps on AWS OpsWorks
Continuous deployment of Rails apps on AWS OpsWorks
 
Aws lambda best practices - ignite - dev opsdays-charlotte
Aws lambda   best practices - ignite - dev opsdays-charlotteAws lambda   best practices - ignite - dev opsdays-charlotte
Aws lambda best practices - ignite - dev opsdays-charlotte
 
Cortex: Prometheus as a Service, One Year On
Cortex: Prometheus as a Service, One Year OnCortex: Prometheus as a Service, One Year On
Cortex: Prometheus as a Service, One Year On
 

Similar to Node js with steroids

Node.js Native AddOns from zero to hero - Nicola Del Gobbo - Codemotion Rome ...
Node.js Native AddOns from zero to hero - Nicola Del Gobbo - Codemotion Rome ...Node.js Native AddOns from zero to hero - Nicola Del Gobbo - Codemotion Rome ...
Node.js Native AddOns from zero to hero - Nicola Del Gobbo - Codemotion Rome ...
Codemotion
 
Nodejs overview
Nodejs overviewNodejs overview
Nodejs overview
Nicola Del Gobbo
 
Beginners Node.js
Beginners Node.jsBeginners Node.js
Beginners Node.js
Khaled Mosharraf
 
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
David Voyles
 
Best of Microsoft Dev Camp 2015
Best of Microsoft Dev Camp 2015Best of Microsoft Dev Camp 2015
Best of Microsoft Dev Camp 2015
Bluegrass Digital
 
React Tech Salon
React Tech SalonReact Tech Salon
React Tech Salon
Chenguang ZHANG
 
Deno Crate Organization
Deno Crate OrganizationDeno Crate Organization
Deno Crate Organization
Anthony Campolo
 
Node.js Development with Apache NetBeans
Node.js Development with Apache NetBeansNode.js Development with Apache NetBeans
Node.js Development with Apache NetBeans
Ryan Cuprak
 
Mini .net conf 2020
Mini .net conf 2020Mini .net conf 2020
Mini .net conf 2020
Marco Parenzan
 
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
 
What is Mean Stack Development ?
What is Mean Stack Development ?What is Mean Stack Development ?
What is Mean Stack Development ?
Balajihope
 
Introduction to Meteor - revised edition
Introduction to Meteor - revised editionIntroduction to Meteor - revised edition
Introduction to Meteor - revised edition
Stephan Hochhaus
 
Delivering Developer Tools at Scale
Delivering Developer Tools at ScaleDelivering Developer Tools at Scale
Delivering Developer Tools at Scale
Oracle Developers
 
20120306 dublin js
20120306 dublin js20120306 dublin js
20120306 dublin js
Richard Rodger
 
MongoDB World 2016: Get MEAN and Lean with MongoDB and Kubernetes
MongoDB World 2016: Get MEAN and Lean with MongoDB and KubernetesMongoDB World 2016: Get MEAN and Lean with MongoDB and Kubernetes
MongoDB World 2016: Get MEAN and Lean with MongoDB and Kubernetes
MongoDB
 
Kalp Corporate Node JS Perfect Guide
Kalp Corporate Node JS Perfect GuideKalp Corporate Node JS Perfect Guide
Kalp Corporate Node JS Perfect Guide
Kalp Corporate
 
Docker Introduction
Docker IntroductionDocker Introduction
Docker Introduction
Jeffrey Ellin
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operator
kamal kotecha
 
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
Amazon Web Services
 
Erica Cooksey Reactathon 2018
Erica Cooksey Reactathon 2018Erica Cooksey Reactathon 2018
Erica Cooksey Reactathon 2018
🏡 Erica Cooksey
 

Similar to Node js with steroids (20)

Node.js Native AddOns from zero to hero - Nicola Del Gobbo - Codemotion Rome ...
Node.js Native AddOns from zero to hero - Nicola Del Gobbo - Codemotion Rome ...Node.js Native AddOns from zero to hero - Nicola Del Gobbo - Codemotion Rome ...
Node.js Native AddOns from zero to hero - Nicola Del Gobbo - Codemotion Rome ...
 
Nodejs overview
Nodejs overviewNodejs overview
Nodejs overview
 
Beginners Node.js
Beginners Node.jsBeginners Node.js
Beginners Node.js
 
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
 
Best of Microsoft Dev Camp 2015
Best of Microsoft Dev Camp 2015Best of Microsoft Dev Camp 2015
Best of Microsoft Dev Camp 2015
 
React Tech Salon
React Tech SalonReact Tech Salon
React Tech Salon
 
Deno Crate Organization
Deno Crate OrganizationDeno Crate Organization
Deno Crate Organization
 
Node.js Development with Apache NetBeans
Node.js Development with Apache NetBeansNode.js Development with Apache NetBeans
Node.js Development with Apache NetBeans
 
Mini .net conf 2020
Mini .net conf 2020Mini .net conf 2020
Mini .net conf 2020
 
2016 07 - CloudBridge Python library (XSEDE16)
2016 07 - CloudBridge Python library (XSEDE16)2016 07 - CloudBridge Python library (XSEDE16)
2016 07 - CloudBridge Python library (XSEDE16)
 
What is Mean Stack Development ?
What is Mean Stack Development ?What is Mean Stack Development ?
What is Mean Stack Development ?
 
Introduction to Meteor - revised edition
Introduction to Meteor - revised editionIntroduction to Meteor - revised edition
Introduction to Meteor - revised edition
 
Delivering Developer Tools at Scale
Delivering Developer Tools at ScaleDelivering Developer Tools at Scale
Delivering Developer Tools at Scale
 
20120306 dublin js
20120306 dublin js20120306 dublin js
20120306 dublin js
 
MongoDB World 2016: Get MEAN and Lean with MongoDB and Kubernetes
MongoDB World 2016: Get MEAN and Lean with MongoDB and KubernetesMongoDB World 2016: Get MEAN and Lean with MongoDB and Kubernetes
MongoDB World 2016: Get MEAN and Lean with MongoDB and Kubernetes
 
Kalp Corporate Node JS Perfect Guide
Kalp Corporate Node JS Perfect GuideKalp Corporate Node JS Perfect Guide
Kalp Corporate Node JS Perfect Guide
 
Docker Introduction
Docker IntroductionDocker Introduction
Docker Introduction
 
basic core java up to operator
basic core java up to operatorbasic core java up to operator
basic core java up to operator
 
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
 
Erica Cooksey Reactathon 2018
Erica Cooksey Reactathon 2018Erica Cooksey Reactathon 2018
Erica Cooksey Reactathon 2018
 

More from Nicola Del Gobbo

Next Generation N-API
Next Generation N-APINext Generation N-API
Next Generation N-API
Nicola Del Gobbo
 
Nodejs from zero to hero
Nodejs from zero to heroNodejs from zero to hero
Nodejs from zero to hero
Nicola Del Gobbo
 
Expressjs from-zero-to-hero
Expressjs from-zero-to-heroExpressjs from-zero-to-hero
Expressjs from-zero-to-hero
Nicola Del Gobbo
 
Introduzione a Node.js
Introduzione a Node.jsIntroduzione a Node.js
Introduzione a Node.js
Nicola 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 tecnologie
Nicola 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 profiling
Nicola Del Gobbo
 
Lexgenda
LexgendaLexgenda

More from Nicola Del Gobbo (7)

Next Generation N-API
Next Generation N-APINext Generation N-API
Next Generation N-API
 
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

Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
shyamraj55
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
DianaGray10
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
Neo4j
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
Rohit Gautam
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Aggregage
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
innovationoecd
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
KatiaHIMEUR1
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
Aftab Hussain
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Speck&Tech
 
20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website
Pixlogix Infotech
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
DianaGray10
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
Neo4j
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 

Recently uploaded (20)

Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with SlackLet's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slack
 
UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5UiPath Test Automation using UiPath Test Suite series, part 5
UiPath Test Automation using UiPath Test Suite series, part 5
 
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...
 
Large Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial ApplicationsLarge Language Model (LLM) and it’s Geospatial Applications
Large Language Model (LLM) and it’s Geospatial Applications
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
Generative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionGenerative AI Deep Dive: Advancing from Proof of Concept to Production
Generative AI Deep Dive: Advancing from Proof of Concept to Production
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
Presentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of GermanyPresentation of the OECD Artificial Intelligence Review of Germany
Presentation of the OECD Artificial Intelligence Review of Germany
 
Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !Securing your Kubernetes cluster_ a step-by-step guide to success !
Securing your Kubernetes cluster_ a step-by-step guide to success !
 
Removing Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software FuzzingRemoving Uninteresting Bytes in Software Fuzzing
Removing Uninteresting Bytes in Software Fuzzing
 
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?
 
20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website20 Comprehensive Checklist of Designing and Developing a Website
20 Comprehensive Checklist of Designing and Developing a Website
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1Communications Mining Series - Zero to Hero - Session 1
Communications Mining Series - Zero to Hero - Session 1
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
GraphSummit Singapore | Graphing Success: Revolutionising Organisational Stru...
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 

Node js with steroids

  • 1. Node.js With Steroids Make Better Node.js Application with Native Add-Ons Nicola Del Gobbo, Developer, Packly
  • 2. Who is Nicola Del Gobbo? Developer Contribute to
  • 3. What is Node.js Native Addon? In a very simple way Native Addons could be considered as C / C++ code called from JavaScript BRIDGE Native environment JavaScript environment
  • 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 should you implement new Native Add-on? Performance In general C / C++ code performs better than JavaScript code, but it’s really true for CPU bounds operations • 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 should you implement new Native Add-on? Integrate legacy application You have the source code of an old C / C++ application and want to expose something of its functionalities through the new Node.js application
  • 8. Why should you implement new Native Add-on? You don’t find what fits your specific needs on npm Sometimes completely reimplementing the module in JavaScript is not the right solution Think at libraries like: • ImageMagick • Ghostscript • FFmpeg • TensorFlow You have to concentrate on business logic of your application and not on developing a single module
  • 9. Why should you implement new Native Add-on? Desktop application You want to use the local underlying CPU or GPU resources to execute the most complex tasks Es. Electron or NW.js • Better performance on the local side • Better performance on the server
  • 10. Why should you implement new Native Add-on? 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
  • 11. Problems Fragmentation 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 The API to implement Native Add-Ons have been changed across different version of Node.js Most of the changes were on V8 API and ObjectWrap API For more info http://v8docs.nodesource.com/
  • 12. Problems Fragmentation API 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
  • 13. Problems Write portable C / C++ code At one point your native code must compile on different: ARCHITECTURE PLATFORM COMPILER
  • 14. 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 concepts about Native Add-Ons
  • 15. How to organize your native Addon project src C/C++ code and maybe dependencies binding.gyp building configurations lib JavaScript code package.json
  • 17. Example: the C / C++ part
  • 18. Example: the binding.gyp Sometimes finding the right settings for binding.gyp is not easy Refer to GYP documentation https://gyp.gsrc.io/docs/UserDocumentation.md More useful examples to take inspiration from other developers https://github.com/nodejs/node-gyp/wiki/”binding.gyp”-files-out-in-the-wild
  • 19. Which kind of Addon should you implement? TIME: Amount of processing time spent on the C++ code DATA: Amount of data flowing between C++ and JavaScript
  • 22. ObjectWrap API • 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.
  • 24. Lessons learned from my experience • Create simple interface between C / C++ and JavaScript • Insert complexity on the JavaScript side • 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 Addons on a distributed system • Use Buffer to pass big quantity of data • If you have many parameters use JSON to pass and parse data • Consider the using of protobuf
  • 25. Present and future • The largest number of native addons is written using NAN • NAN helps stay compatible with old versions of Node.js • N-API will be a game changer on the native addon development • ABI compatibility • New ES6 types • Isolated from V8 API (VM agnostic) • C / C++ • Conversion tool that helps to migrate from NAN • Great developer experience for mantainers
  • 26. Implement high performance key value database Binding to Vedis an embeddable datastore C library https://github.com/NickNaso/conf-ni- 2017
  • 27. Thanks! nicoladelgobbo@gmail.com @NickNaso on Twitter All examples and materials are here https://github.com/NickNaso/conf-ni- 2017

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
  9. 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
  10. In the example we can see the JavaScript part of bcrypt addon. For who of you that don’t know it: Bcrypt is a module that help us to hash passwords. In the reported portion of code it import the addon and call its function: gen_salt_sync. To understand how to create this function we have to take a look at C / C++ part of the module
  11. What happen here? The macro NODE_MODULE creates code that will register a module named ”bcypt_lib” 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 gen_salt_sync and you can find the code executed by this function in the method GenerateSaltSync. 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.
  12. 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.
  13. We can categorize the different use cases for addons considering the amount of time we’ll spend in the C++ code and the amount of data flowing between C++ and JavaScript. If you are in the left quadrant maybe your native addon can be synchronous and this means that the native code will be executed directly on the event loop when called. In the right quadrants for sure, you have to implement the addon using the asynchronous pattern. The difference between the top and bottom quadrants is often overlooked, but it is equally important. Sometimes the cost of copying all data between JvaScript to C++ and vice versa usually kills the performance benefits you obtained from C++. In this scenarios we should consider to use the Buffer to pass the data because it uses the memory outside the V8 heap, this means that it’s not subject to the multi-threading rules of V8 and we can interact with it in place from a C++.
  14. 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.
  15. Store a reference to this constructor so it can be called in New if New is called without constructor syntax